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.

Info

If the find() method can’t find any element that satisfies the condition, it returns undefined:

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, 'Sarah');
console.log(key); // undefined

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.



Every Crazy Thing JavaScript Does

A captivating guide to the subtle caveats and lesser-known parts of JavaScript.

Every Crazy Thing JavaScript Does

Sign up and receive a free copy immediately.

1 thought on “How to Get an Object Key by Its Value in JavaScript”

Leave a Comment

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