How to useArray.from() and forEach() Method in Javascript
The Array.from() method can be used to convert the iterable returned by Map.entries() into an array of [key, value] pairs. This array can then be iterated using the forEach() method.
Syntax:
Array.from(myMap.entries()).forEach(([key, value]) => {
console.log(key + " is " + value);
});
Example: This example demonstrates the implementation of the above-explained approach.
function iterateMap() {
let myMap = new Map();
myMap.set("Cricket", "sport");
myMap.set("Apple", "fruit");
Array.from(myMap.entries()).forEach(([key, value]) => {
console.log(key + " is " + value);
});
}
iterateMap();
Output
Cricket is sport Apple is fruit
How to iterate over Map elements in JavaScript ?
Map() is very useful in JavaScript it organises elements into key-value pairs. This method iterates over each element in an array and applies a callback function to it, allowing for modifications before returning the updated array.”
The Map() keyword is used to generate the object. The map() method loops through each object in the given array. The map() method combines with the entries() method to loop through the object and returns an array containing key-value pairs as its data.
Here we have two methods to iterate Map element in JavaScript:
Table of Content
- Using for…of loop
- Using forEach() loop
- Using Map.keys() method
Contact Us