How to Get a Key in a Javascript Object By Its Value

 
 
 
As always, there are multiple ways to solve this problem. In this tutorial, we are going to explain one of the simplest methods to access a key name by its value.
 
In the following example, we are going to enter a text in the input element and upon click of a button, we want to find its corresponding key in the object and display it on the screen. Please have a look over the code example and steps given below.
 
HTML & CSS:
body {
    text-align: center;
}

div {
    display: inline-block;
}

input, button{
    display: inline-block;
    padding: 10px 20px;
}

Javascript

  • We have selected all 3 elements button, input, and h1 using the document.querySelector() method and stored them in btn, input, and result variables respectively.
  • We have created one global object obj which has 3 properties.
  • We have attached the click event listener to the button element. Inside the click event handler, we are simply accessing the value entered in the input element and assigning it to the value variable.
  • Object.keys() method takes an object obj as a parameter and returns an array that includes all the keys in the object.
  • In general, the find() method will return the first element from the array which meets a certain condition.
  • We will execute our find() method on the keys array to find the corresponding key based on the value entered in the input field and display it on the screen inside the h1 element.
let btnGet = document.querySelector('button');
let input = document.querySelector('input');
let result = document.querySelector('h1');


let obj= {
    james: '100',
    peter:'200',
    marks:'300'
}

btnGet.addEventListener('click', () => {
    let value = input.value;
    result.innerText = Object.keys(obj).find(key => obj[key] == value);
});