Javascript Object: Find the Key(s) of a given Value

Last updated on June 23, 2022 A Goodman Loading... Post a comment

This practical, concise article shows you a couple of different ways to get the key if know its value in a Javascript object. Without any further ado, let’s write some code.

Caveat: It is possible that an object has some properties with different keys but the same value. We have to find all the keys (if there is more than one) that match the input value. If go too fast, we may miss results.

The modern way (ES6 and later)

We can use the Array.filter() method to quickly solve the task.

Example:

// define a reusable function
const getKey = (object, value) => {
    // Get the array of keys
    const keys = Object.keys(object);

    // Get all keys that match the value
    // Becasue it's possible that mutliple keys match the same value, we need to use the filter() method instead of the find() method
    return keys.filter(key => object[key] === value);
}

// try it
var obj = {
    'key1': 'Dog',
    'key2': 'Cat',
    'key3': 'Dog',
    'key4': 'Dragon',
    'key5': 'Crocodile'
}

console.log("Key(s) of 'Dog':", getKey(obj, 'Dog'));
console.log("Key(s) of 'Dragon':", getKey(obj, 'Dragon'));

Output:

Key(s) of 'Dog': (2) ['key1', 'key3']
Key(s) of 'Dragon': ['key4']

The traditional way

We can loop through the given object and check each key one by one.

Example code with explanation:

// define a reusable function
function getKey(object, value){
    // get the array of keys
    var keys = Object.keys(object);
    
    // there might be more than one keys with the same value
    // so we store the found keys
    var results = [];

    for (var i = 0; i < keys.length; i++) {
        if (object[keys[i]] === value){
            results.push(keys[i]);
        }
    }

    return results;
}

// try it
var obj = {
    'a': 11,
    'b': 20,
    'c': 8,
    'd': 15,
    'e': 25,
    'f': 8
}

console.log("Key(s) of '8':", getKey(obj, 8));
console.log("Key(s) of '15':", getKey(obj, 15));

Output:

Key(s) of '8': (2) ['c', 'f']
Key(s) of '15': ['d']

Conclusion

You’ve learned how to get the keys that match a known value in a Javascript object. If you’d like to explore more new and interesting stuff about modern Javascript and web technologies, take a look at the following articles:

You can also check out our Javascript category page, TypeScript category page, Node.js category page, and React category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles