JavaScript: Get the Key of an Object Property by Its Value

Updated: March 14, 2023 By: Khue Post a comment

When developing websites and applications with JavaScript, there might be times when you need to retrieve the key of an object property by its value. This task can be done in several different ways. Let’s explore them, one by one, in this concise example-based article.

Using the Object.keys() and find() methods

You can use the Object.keys() method to get an array of keys and then use the Array.prototype.find() method to find the key that matches the value.

Example:

const myObject = {
    name: 'Sling Academy',
    age: 10
}

const value = 'Sling Academy';

// Find the key of the object that has the value 'Sling Academy'
const result = Object.keys(myObject).find(key => myObject[key] === value);

// Print the result
if(result){
    console.log(result); 
} else {
    console.log('Key not found');
}

Output:

name

This approach is quick and elegant. The main logic only requires a single line of code.

Using a for…in loop

You can also use a for…in loop to iterate over the object’s properties and compare them with the given value.

Example:

// define a reusable function
const getKeyByValue1 = (object, value) => {
  for (var key in object) {
    if (object.hasOwnProperty(key) && object[key] === value) {
      return key;
    }
  }
};

// try it out
const obj = { a: 1, b: 2, c: 3 };
console.log(getKeyByValue1(obj, 2)); 

Output:

b

Using the Object.entries() and reduce() methods

This solution converts the object to an array of [key, value] pairs using Object.entries() and reduces the array to the first key that has the target value.

Example:

// define a reusable function
const getKeyByValue = (object, value) => {
  return Object.entries(object).reduce(
    (acc, [key, val]) => (val === value ? key : acc),
    null
  );
};

// Example usage
const obj = {'slingAcademy': 1, 'blue': 2, 'green': 3}
const value = 1;
console.log(getKeyByValue(obj, value)); 

Output:

slingAcademy

Afterword

We’ve walked through a couple of different ways to find an object key by a provided value in modern JavaScript (arrow functions, new built-in methods). None of them is verbose or longer than necessary. Pick the one you like to go with.

If you find errors or anachronisms in the code examples, please let us know by leaving comments. We will review and update them as soon as possible.