HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Find matching keys in a JavaScript object

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptobjectfindmatchingkeys

Problem

JavaScript objects are commonly used as dictionaries, where the keys are used to identify some values. In such cases, it is often useful to find all the keys that match a given value or condition.
Using Object.keys(), you can get all the keys of an object as an array. You can then use Array.prototype.filter() to test each key-value pair and return all keys that match the given condition.
If you want to simply test against a value, the implementation can be simplified to accept a single value, instead of a function. In the demonstrated generic implementation, the callback receives three arguments - the value, the key and the object.
Using Array.prototype.filter() is inefficient if you only need the first matching key. In this scenario, Array.prototype.find() is the better choice.
Recent versions of JavaScript also added Array.prototype.findLast() which can be used to find the last matching key.

Solution

const findKeys = (obj, fn) =>
  Object.keys(obj).filter(key => fn(obj[key], key, obj));

const ages = {
  Leo: 20,
  Zoey: 21,
  Jane: 20,
};
findKeys(ages, x => x === 20); // [ 'Leo', 'Jane' ]


If you want to simply test against a value, the implementation can be simplified to accept a single value, instead of a function. In the demonstrated generic implementation, the callback receives three arguments - the value, the key and the object.
Using Array.prototype.filter() is inefficient if you only need the first matching key. In this scenario, Array.prototype.find() is the better choice.
Recent versions of JavaScript also added Array.prototype.findLast() which can be used to find the last matching key.
For older JavaScript versions, you'll have to use Array.prototype.reverse() to reverse the order of the keys and then use Array.prototype.find() to find the last matching key.
> [!WARNING]
>

Code Snippets

const findKeys = (obj, fn) =>
  Object.keys(obj).filter(key => fn(obj[key], key, obj));

const ages = {
  Leo: 20,
  Zoey: 21,
  Jane: 20,
};
findKeys(ages, x => x === 20); // [ 'Leo', 'Jane' ]
const findKey = (obj, fn) =>
  Object.keys(obj).find(key => fn(obj[key], key, obj));

findKey(
  {
    barney: { age: 36, active: true },
    fred: { age: 40, active: false },
    pebbles: { age: 1, active: true }
  },
  x => x['active']
); // 'barney'
const findLastKey = (obj, fn) =>
  Object.keys(obj).findLast(key => fn(obj[key], key, obj));

findLastKey(
  {
    barney: { age: 36, active: true },
    fred: { age: 40, active: false },
    pebbles: { age: 1, active: true }
  },
  x => x['active']
); // 'pebbles'

Context

From 30-seconds-of-code: find-matching-keys

Revisions (0)

No revisions yet.