How to get the Value by a Key in JavaScript Map?
Last Updated :
15 Mar, 2024
JavaScript Map is a powerful data structure that provides a convenient way to store key-value pairs and retrieve values based on keys. This can be especially useful when we need to associate specific data with unique identifiers or keys.
Different Approaches to Get the Value by a Key in JavaScript Map
1. Using the get() method
The get method of the Map object is used to retrieve the value associated with a specified key.
Syntax:
map.get(key)
Example: This example uses the, get method to retrieve the value.
Javascript
let map = new Map();
map.set('name', 'GeeksforGeeks');
map.set('CEO', 'Sandeep Jain');
console.log(map.get('name'));
console.log(map.get('CEO'));
OutputGeeksforGeeks
Sandeep Jain
2. Using forEach method
In this approach, iterate we will use forEach method to iterates over each key-value pair in the Map. It takes a callback function as an argument, which is called with each key and value in the Map. In this case, the callback function checks if the key matches the desired key and assigns the corresponding value to the value variable.
Syntax:
Object.forEach(function(currentValue, index) {
});
Example: Below example use forEach method to retrieve the value of provided key.
Javascript
let map = new Map();
map.set('name', 'GeeksforGeeks');
map.set('CEO', 'Sandeep Jain');
map.set("est", 2009)
let value;
map.forEach((val, key) => {
if (key === 'name') {
value = val;
}
});
console.log(value);
3. Using Array.from() and find() method
In this approach, we are using Array.from() to convert the Map entries into an array of key-value pairs. Then, we apply the find() method to search for the entry where the key matches the specified key.
Syntax
Array.from(object, mapFunction, thisValue)
array.find(function(currentValue, index, arr), thisValue)
JavaScript
const map = new Map();
map.set('name', 'GeeksforGeeks');
map.set('CEO', 'Sandeep Jain');
const key = 'name';
const value = Array.from(map).find(([k, v]) => k === key)?.[1];
console.log(value);
Share your thoughts in the comments
Please Login to comment...