Get a Object's Key by its Value using JavaScript

avatar

Borislav Hadzhiev

Fri Oct 29 20212 min read

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

To get an object's key by it's value, call the Object.keys() method to get an array of the object's keys. Then use the find() method to find the key that corresponds to the value. 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 will return 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
Note that 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"

If you need to get the values of multiple keys that store the same value, you can switch the find method to filter.

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 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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee