Open In App

How to get a key in a JavaScript object by its value ?

In this article, we will learn how to get a key in a JavaScript object by its value. The values of the object can be found by iterating through its properties. Each of these properties can be checked to see if they match the value provided.

How to get a key in a JavaScript object by its value?

Below are the approaches through which we get a key in a JavaScript object by its value:



Method 1: Using a for-in loop

Example: This example is the implementation of the above-explained approach.






function getKeyByValue(object, value) {
    for (let prop in object) {
        if (object.hasOwnProperty(prop)) {
            if (object[prop] === value)
                return prop;
        }
    }
}
 
const exampleObject = {
    key1: 'Geeks',
    key2: 100,
    key3: 'Javascript'
};
 
ans = getKeyByValue(exampleObject, 100);
 
console.log(ans);

Output
key2

Method 2: Using the find Method()

Note: This method was added to the ES6 specification and may not be supported on older browser versions.

Example: This example is the implementation of the above-explained approach.




function getKeyByValue(object, value) {
    return Object.keys(object).find(key =>
        object[key] === value);
}
 
const exampleObject = {
    key1: 'Geeks',
    key2: 100,
    key3: 'Javascript'
};
 
ans = getKeyByValue(exampleObject, 'Geeks');
console.log(ans);

Output
key1

Method 3: Using filter() Method and Object keys() Method

Example: This example is the implementation of the above-explained approach.




function getKeyByValue(obj, value) {
    return Object.keys(obj)
           .filter(key => obj[key] === value);
}
 
const exampleObject = {
    key1: 'Geeks',
    key2: 100,
    key3: 'Javascript'
};
 
ans = getKeyByValue(exampleObject, 'Geeks');
console.log(ans);

Output
[ 'key1' ]

Method 4: Using Object.entries() and reduce() Method

Example: This example is the implementation of the above-explained approach.




function getKeyByValue(obj, value) {
    return Object.entries(obj)
    .reduce((acc, [key, val]) => {
        if (val === value) {
            acc.push(key);
        }
        return acc;
    }, []);
}
 
const exampleObject = {
    key1: 'Geeks',
    key2: 100,
    key3: 'Javascript'
};
 
ans = getKeyByValue(exampleObject, 'Geeks');
console.log(ans);

Output
[ 'key1' ]

Method 5: Using Lodash _.findKey() Method

Example: This example is the implementation of the above-explained approach.




// Requiring the lodash library
const _ = require("lodash");
 
// Original array
let users = {
    'meetu': { 'salary': 36000, 'active': true },
    'teetu': { 'salary': 40000, 'active': false },
    'seetu': { 'salary': 10000, 'active': true }
};
 
// Using the _.findKey() method
// The `_.matches` iteratee shorthand
let found_elem = _.findKey(users, {
    'salary': 10000,
    'active': true
});
 
// Printing the output
console.log(found_elem);

Output:

seetu

Article Tags :