Get an Object's Key by its Value using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Get an Object's Key by its Value in JavaScript #

To get an object's key by it's value:

  1. Call the Object.keys() method to get an array of the object's keys.
  2. Use the find() method to find the key that corresponds to the value.
  3. The find method will return the first key that satisfies the condition.
index.js
function getObjKey(obj, value) { return Object.keys(obj).find(key => obj[key] === value); } const obj = {country: 'Chile', city: 'Santiago'}; console.log(getObjKey(obj, 'Chile')); // 👉️ "country"

We used the Object.keys method to get an array containing the object's keys.

index.js
const obj = {country: 'Chile', city: 'Santiago'}; console.log(Object.keys(obj)); // 👉️ ['country', 'city']

Then, we called the Array.find method on the keys array.

The function we passed to the find() method gets called with each element (key) in the array until it returns a truthy value or iterates over the entire array.

On each iteration, we use the key to access the object's value and compare it to the supplied value.

If equality check succeeds, the find method returns the corresponding key and short-circuits.

If the equality check never returns true, the find method returns undefined.

index.js
function getObjKey(obj, value) { return Object.keys(obj).find(key => obj[key] === value); } const obj = {country: 'Chile', city: 'Santiago'}; console.log(getObjKey(obj, 'DoesNotExist')); // 👉️ undefined
The find method returns the first element that satisfies the testing function. If you have multiple keys with the same value, you would get the name of the first key.
index.js
function getObjKey(obj, value) { return Object.keys(obj).find(key => obj[key] === value); } const obj = {city1: 'Santiago', city2: 'Santiago'}; console.log(getObjKey(obj, 'Santiago')); // 👉️ "city1"

To get multiple object keys that store the same value:

  1. Call the Object.keys() method to get an array of the object's keys.
  2. Call the Array.filter() method on the array of keys.
  3. The filter() method will return a new array containing all the matching keys.
index.js
function getObjKeys(obj, value) { return Object.keys(obj).filter(key => obj[key] === value); } const obj = {city1: 'Santiago', city2: 'Santiago'}; // 👇️️ ["city1", "city2"] console.log(getObjKeys(obj, 'Santiago'));

By using the Array.filter method we get an array of all the keys that satisfy the condition.

The function we passed to the filter() method gets called for each key in the array and does not short-circuit on the first truthy response.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.