June 27, 2020
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
, andh1
using thedocument.querySelector()
method and stored them inbtn
,input
, andresult
variables respectively. - We have created one global object
obj
which has 3 properties. - We have attached the
click
event listener to thebutton
element. Inside theclick
event handler, we are simply accessing the value entered in theinput
element and assigning it to thevalue
variable. Object.keys()
method takes an objectobj
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 theinput
field and display it on the screen inside theh1
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); });
div
,input
,button
, andh1
). The div element is just a wrapper for the rest of the elements.style.css
stylesheet inside thehead
element.script.js
with ascript
tag at the bottom.