Categories
JavaScript Answers

How to Get a Key in a JavaScript Map by its Value?

Spread the love

To get a key in a JavaScript map by its value, we can use the spread operator to spread the entries into an array.

Then we can use the filter method to return an array with the entries with the given value.

For instance, we can write:

const people = new Map();
people.set('1', 'john');
people.set('2', 'jasmin');
people.set('3', 'foo');

const keys = [...people.entries()]
  .filter(([, v]) => v === 'john')
  .map(([k]) => k);

console.log(keys);

We create the people map with a few entries.

And we want to find the key for the entry with 'john' as its value.

To do this, we call people.entries() to return an iterator with the key-value pair arrays from the map.

Then we spread the iterator entries into an array with the spread operator.

Next, we call filter with a callback that destructures the v map value from the parameter.

And we return the entries where value v is 'john'.

Finally, we call map to map the k keys from the map and return them in the returned array.

Therefore, keys is ["1"] as we can see from the console log.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.