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'
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.
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.
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'))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With