Javascript: Get Key by Value

While working in javascript, often there is a requirement to get the key of an object for a particular value. This article will discuss accessing the key of a javascript object by value.

Table of Contents:-

Get key by value using loop

Example:-

  • Get the key for value ‘Monroe’
  • Get the key for value ‘Santiago’
  • Get the key for value ‘xyz’

Code:-

function findKey(object, value) 
{
    var keyArr=[];
    for (let key in object)
    {
        if (object[key] === value) 
        {
            keyArr.push(key);
        }
    }
    if(keyArr.length >0 )
    {
    return keyArr;
    }
    else
    {
        return "Not Found";
    }
}
// object definition
let cityInfo = {
    George   : "Santiago",
     Veronica  : "Monroe",
     Paul : "NewYork",
     Mounika : "Santiago"
 };
// usage of function findKey()
console.log("Key is " + findKey(cityInfo, "Monroe"));
console.log("Key is "+ findKey(cityInfo, "Santiago"));
console.log("Key is " + findKey(cityInfo, "xyz"));

Output:-

Key is Veronica
Key is George,Mounika
Key is Not Found

Explanation:-

  • Here, a loop is run till the number of keys in the object.
  • Inside the loop, the value for every key is accessed. If the value is the same as passed in the function, it is pushed in an array. An array is used so that multiple keys with the same value are handled.
  • Finally, return the array. If the array is empty, then return the string “Not Found”.

Get first element of an array using Object.keys() and Object.values()

  • Object.keys() return the array of keys of the corresponding object.
  • Object.values() return the array of values of the corresponding object.

Example:-

  • Get the key for value ‘Monroe’
  • Get the key for value ‘Santiago’
  • Get the key for value ‘xyz’

Using indexOf() :-

Code:-

function findKey(obj, value) 
 {
    let keys= Object.keys(obj);
    let values =Object.values(obj);
    if(values.includes(value))
    {
        return keys[values.indexOf(value)];   // using indexOf()
    }
    else
    {    
        return "Not Found";  
    }
 }
// object definition
let cityInfo = {
    George   : "Santiago",
     Veronica  : "Monroe",
     Paul : "NewYork",
     Mounika : "Santiago"
 };
// usage of function findKey()
 console.log("Key is " + findKey(cityInfo, "Monroe"));
 console.log("Key is "+ findKey(cityInfo, "Santiago"));
 console.log("Key is " + findKey(cityInfo, "xyz"));

Output:-

Key is Veronica
Key is George
Key is Not Found

Explanation:-

  • The code checks if the values array contains the element passed as an argument. If yes, the code gets the index of the particular value passed in as an argument using the indexOf() method and returns it.
  • If the value passed in as an argument is absent in the values array. The string “Not Found” is returned.
  • This solution returns only the first key even if more keys correspond to the same value passed in as an argument.

Using find() :-

Code:-

function findKey(obj, value) 
 {
    let keys= Object.keys(obj);
    let values =Object.values(obj);
    if(values.includes(value))
    {
        return keys.find(key => obj[key] === value);  // using find()
    }
    else
    {    
        return "Not Found";  
    }
 }
// object definition
let cityInfo = {
    George   : "Santiago",
     Veronica  : "Monroe",
     Paul : "NewYork",
     Mounika : "Santiago"
 };
// usage of function findKey()
 console.log("Key is " + findKey(cityInfo, "Monroe"));
 console.log("Key is "+ findKey(cityInfo, "Santiago"));
 console.log("Key is " + findKey(cityInfo, "xyz"));

Output:-

Key is Veronica
Key is George
Key is Not Found

Explanation:-

  • Here find() method is used to get the first key found corresponding to the specified value passed in as argument.
  • The find() method in javascript returns the first element in the array that satisfies the provided functionality. Therefore only George is returned for value “Santiago”.

Using filter() :-

Code:-

function findKey(obj, value) 
 {
    let keys= Object.keys(obj);
    let values =Object.values(obj);
    if(values.includes(value))
    {
        return keys.filter(key => obj[key] === value); // For ES6 + 1 Liners using the filter() method
    }
    else
    {    
        return "Not Found";  
    }
 }
// object definition
let cityInfo = {
    George   : "Santiago",
     Veronica  : "Monroe",
     Paul : "NewYork",
     Mounika : "Santiago"
 };
// usage of function findKey()
 console.log("Key is " + findKey(cityInfo, "Monroe"));
 console.log("Key is "+ findKey(cityInfo, "Santiago"));
 console.log("Key is " + findKey(cityInfo, "xyz"));

Output:-

Key is Veronica
Key is George,Mounika
Key is Not Found

Explanation:-

  • Here filter() method is used to get all the keys corresponding to the specified value passed in as an argument.
  • The filter() method in javascript returns all the elements that pass the specified test implemented by provided function. Therefore George and Mounika are returned for value “Santiago”.

Get key by value using Object.entries()

  • Object.entries() returns an array of key and value pairs of the given object.

Example:-

  • Get the key for value ‘Monroe’
  • Get the key for value ‘Santiago’
  • Get the key for value ‘xyz’

Code:-

 function findKey(obj, value) 
 {   
    var keyArr=[];
    for (const [key, val] of Object.entries(obj)) 
    {
        if (val === value) {
            keyArr.push(key);
        }
    }
    if(keyArr.length >0 )
        {
        return keyArr;
        }
        else
        {
            return "Not Found";
        }
 }
// object definition
let cityInfo = {
    George   : "Santiago",
     Veronica  : "Monroe",
     Paul : "NewYork",
     Mounika : "Santiago"
 };
// usage of function findKey()
console.log("Key is " + findKey(cityInfo, "Monroe"));
console.log("Key is "+ findKey(cityInfo, "Santiago"));
console.log("Key is " + findKey(cityInfo, "xyz"));

Output:-

Key is Veronica
Key is George,Mounika
Key is Not Found

Explanation:-

  • Here, a loop is run till the number of [key, value] pairs in the object.
  • Within loop: If [key, value] pair matches with the value passed in as an argument, its key is pushed in an array.
  • Finally, return the array. If the array is empty, then return the string “Not Found”.

Get key by value using map()

  • Object.map() method creates an array with the results of calling a function on every element of the calling array.

Example:-

  • Get the key for value ‘Monroe’
  • Get the key for value ‘Santiago’
  • Get the key for value ‘xyz’

Code:-

function findKey(obj, val) 
{
    var keyFound = "";
    Object.keys(obj).map(function(i)
        {   
            if( obj[i] === val)
            {
                console.log("Key with value: " + i +" = "+ obj[i]) ;
                keyFound = i;
            }
            })
        if(keyFound === "" )
        {
            console.log("Key Not Found") ;
        }

}
// object definition
let cityInfo = {
    George   : "Santiago",
     Veronica  : "Monroe",
     Paul : "NewYork",
     Mounika : "Santiago"
 };
// usage of function findKey()
findKey(cityInfo, "Monroe");
findKey(cityInfo, "Santiago");
findKey(cityInfo, "xyz");

Output:-

Key with value: Veronica = Monroe
Key with value: George = Santiago
Key with value: Mounika = Santiago
Key Not Found

Explanation:-

  • Here, the map() method is applied to the array of object keys.
  • If the value passed in as an argument is equal to any of the key’s corresponding value in the array, it gets printed on the console.
  • If none of the value is matched, “Key Not Found” gets printed on the console.

I hope this article helped you to get the key by value in a javascript object. Good Luck !!!

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top