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

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'))

Leave a Comment