How can I get a key in a JavaScript 'Map' by its value?

There isn't any direct method for picking out information in this direction, so if all you have is the map you need to loop through the set as suggested by others.

If the map/array/other is large enough that such a loop would be a performance issue and the requirement for a reverse lookup is common within the project, you could implement your own structure using a pair of maps/arrays/other with one as per the current object and the other with the key and value reversed.

That way, the reverse lookup is as efficient as the normal one. Of course, you have more work to do as you need to implement each method that you need as a pass-through to one or both of the underlying objects so if the map is small and/or the reverse lookup is not needed often the scan-via-loop option is likely to be preferable due to being simpler to maintain and possible simpler for the JiT compiler to optimise.

In any case, one thing to be wary of is the possibility that multiple keys could have the same value. If this is possible then when looping through your map you need to decide if you are fine to return one of the possible keys arbitrarily (probably the first one) or if you want to return an array of keys, and if implementing a reverse index for data that could have duplicate values the same issue also needs to be accounted for.


Though late and other great answers already exist, still you can give the below "..." and "Array.find" a try:

let people = new Map();
people.set('1', 'jhon');
people.set('2', 'jasmein');
people.set('3', 'abdo');

function getKey(value) {
  return [...people].find(([key, val]) => val == value)[0]
}

console.log('Jasmein - ', getKey('jasmein'))

console.log('Jhon - ', getKey('jhon'))

You could convert it to an array of entries (using [...people.entries()]) and search for it within that array.

let people = new Map();
people.set('1', 'jhon');
people.set('2', 'jasmein');
people.set('3', 'abdo');
    
let jhonKeys = [...people.entries()]
        .filter(({ 1: v }) => v === 'jhon')
        .map(([k]) => k);

console.log(jhonKeys); // if empty, no key found otherwise all found keys.

You can use a for..of loop to loop directly over the map.entries and get the keys.

function getByValue(map, searchValue) {
  for (let [key, value] of map.entries()) {
    if (value === searchValue)
      return key;
  }
}

let people = new Map();
people.set('1', 'jhon');
people.set('2', 'jasmein');
people.set('3', 'abdo');

console.log(getByValue(people, 'jhon'))
console.log(getByValue(people, 'abdo'))