How to Get an Object Key by Its Value in JavaScript

Last updated on December 27, 2022
How to Get an Object Key by Its Value in JavaScript

Object keys() and Array find()

To get the key of an object by value in JavaScript, call the Object.keys() method to get the object keys, then use the find() to find the key associated with the specified value. For example:

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

const obj = {
  user1: 'John',
  user2: 'Kate',
  user3: 'Peter',
};

const key = getObjectKey(obj, 'Kate');
console.log(key); // user2

The Object.keys() method takes an object and returns an array of all its keys:

const obj = {
  user1: 'John',
  user2: 'Kate',
  user3: 'Peter',
};

const keys = Object.keys(obj);
console.log(keys); // [ 'user1', 'user2', 'user3' ]

The Array find() method searches for the element in an array for which a certain condition is true. The condition is specified in the callback testing function passed to find(). The condition we specified only evaluates to true for a key in the array if its corresponding value is equal the value passed to the getObjectKey() function.

Array filter() vs Array find()

The find() method only returns the first element in the array that satisfies the testing function. If the object containing multiple keys with the same value, it will return only the first key it finds:

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

const obj = {
  user1: 'John',
  user2: 'Kate',
  user3: 'Peter',
  user4: 'John',
};

const key = getObjectKey(obj, 'John');
console.log(key); // user1

To get all the keys that correspond to a certain value, you can use the Array filter() method in place of find():

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

const obj = {
  user1: 'John',
  user2: 'Kate',
  user3: 'Peter',
  user4: 'John',
};

const key = getObjectKey(obj, 'John');
console.log(key); // ['user1', 'user4']

Unlike find(), filter() returns an array of all the keys with matching values.

Coding Beauty Assistant logo

Try Coding Beauty AI Assistant for VS Code

Meet the new intelligent assistant: tailored to optimize your work efficiency with lightning-fast code completions, intuitive AI chat + web search, reliable human expert help, and more.

See also