Get object key by value in Javascript

0
52
Get object key by value in Javascript
Get object key by value in Javascript

We can easily get object value by key using index operator object[key], but what about getting object key using value? Today, I will show you a tip to get object key by value in Javascript.

To look up object key using value, we can use Object.keys() to iterate through all key-value pairs, if it matches, the key is found. In other words, this is how we could write the look up function:

function lookupObjectKey(obj, value) {
    return Object.keys(obj).find(key => obj[key] === value);
}

This is the sample test:

console.log(lookupObjectKey(COUNTRY_CODES, 'Canada')); // output: CA
console.log(lookupObjectKey(COUNTRY_CODES, 'United States')); // output: US
console.log(lookupObjectKey(COUNTRY_CODES, 'Brazil')); // output: undefined

Since we use find() method, it will only return only first matching value. If you need to look for more than one matching value, use filter() instead.

function lookupObjectKey(obj, value) { 
    return Object.keys(obj).filter(key => obj[key] === value); 
}

This is a sample test:

const GRADES = {
  "Pete H": "A",
  "John D": "A+",
  "Laura E": "A",
  "Jack C": "B",
  "Jim C": "B+",
}

console.log(lookupObjectKeys(GRADES, "A")); // output: [ 'Pete H', 'Laura E' ]

Alright, that’s how to get object key by value in Javascript.

Have fun!