How to use map.entries() and for…of loop In Javascript
In this approach,
- The Map.prototype.entries() method returns the [key, value] pairs of all the elements of the map in the order of their insertions.
- We use for…of loop to iterate through the entries of the map and check if the value ( the second element in the destructured array [key, value]) matches the searchKeyByValue.
- If the key is found then it is returned; otherwise, we return undefined.
Syntax:
mapObj.entries() //map.entries()
//for..of loop
for ( variable of iterableObjectName) {
...
};
Example: In this example we are using the above-explained apporach.
function keyValue(map, searchKey) {
for (const [key, value] of map.entries()) {
if (value === searchKey)
return key;
}
return undefined;
}
let students = new Map();
students.set('1', 'Diya');
students.set('2', 'Arav');
students.set('3', 'Priyanka');
students.set('4', 'Raj');
console.log(
"Key associated with the value is: " + keyValue(students, 'Diya'));
Output
Key associated with the value is: 1
JavaScript Program to get Key by Value in a Map
In this article, we will see how to get a key by a value in a Map in JavaScript.Getting a key by a specific value in a JavaScript Map refers to finding the corresponding key associated with a given value stored within the Map collection.
Table of Content
- Using map.entries() and for…of loop
- Using Map.forEach()
- Using spread syntax, Array.filter(), and Array.map()
- Using Array.from() and Array.find() method
- Using Array.reduce()
We will explore all the above methods along with their basic implementation with the help of examples.