Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a JavaScript 'Map' like this one

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

I want some method to return a key by its value.

let jhonKey = people.getKey('jhon'); // jhonKey should be '1' 
like image 663
Engineer Passion Avatar asked Nov 06 '17 11:11

Engineer Passion


People also ask

How do you get the key of a Map object?

To get the keys of a Map object, you use the keys() method. The keys() returns a new iterator object that contains the keys of elements in the map.

How do you find the key of an object with its value?

To get an object's key by it's value:Call the Object. keys() method to get an array of the object's keys. Use the find() method to find the key that corresponds to the value. The find method will return the first key that satisfies the condition.


2 Answers

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'))
like image 69
Rajesh Avatar answered Sep 25 '22 10:09

Rajesh


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.
like image 45
Nina Scholz Avatar answered Sep 21 '22 10:09

Nina Scholz