How to use forEach method In Javascript
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.
let map = new Map();
map.set('name', 'w3wiki');
map.set('CEO', 'Sandeep Jain');
map.set("est", 2009)
let value;
map.forEach((val, key) => {
if (key === 'name') {
value = val;
}
});
console.log(value);
Output
w3wiki
How to get the Value by a Key in JavaScript Map?
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.