DEV Community

Avnish
Avnish

Posted on

How to iterate over Map elements in JavaScript ?

1. Using for...of loop

  • Iterates directly over key-value pairs of the Map.
  • Uses destructuring [key, value] to access elements.
let newMap = new Map();
newMap.set("Cricket", "sport");
newMap.set("Apple", "fruit");

for (let [key, value] of newMap) {
    console.log(`${key} is ${value}`);
}
Enter fullscreen mode Exit fullscreen mode

Output:

Cricket is sport
Apple is fruit
Enter fullscreen mode Exit fullscreen mode

2. Using forEach() method

  • Calls a function once for each key-value pair.
let newMap = new Map();
newMap.set("Monday", 1);
newMap.set("Tuesday", 2);
newMap.set("Wednesday", 3);

newMap.forEach((value, key) => {
    console.log(value, key);
});
Enter fullscreen mode Exit fullscreen mode

Output:

1 Monday
2 Tuesday
3 Wednesday
Enter fullscreen mode Exit fullscreen mode

3. Using Map.keys() Method

  • Returns an iterator of the keys, which can be accessed using .next() method.
let myMap = new Map([
    ['a', 1],
    ['b', 3], 
    ['d', 10]
]);

let keys = myMap.keys();

while (true) {
    let result = keys.next();
    if (result.done) break;
    console.log(result.value);
}
Enter fullscreen mode Exit fullscreen mode

Output:

a
b
d
Enter fullscreen mode Exit fullscreen mode

4. Using Array.from() and forEach()

  • Converts Map.entries() to an array and iterates using forEach().
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();
Enter fullscreen mode Exit fullscreen mode

Output:

Cricket is sport
Apple is fruit
Enter fullscreen mode Exit fullscreen mode

5. Using Map.values() Method

  • Returns an iterator of values that can be iterated using for...of loop.
let myMap = new Map();
myMap.set("Dog", "animal");
myMap.set("Banana", "fruit");
myMap.set("Car", "vehicle");

for (let value of myMap.values()) {
    console.log(value);
}
Enter fullscreen mode Exit fullscreen mode

Output:

animal
fruit
vehicle
Enter fullscreen mode Exit fullscreen mode

Each method provides flexibility depending on whether you need keys, values, or key-value pairs. 🎯

Top comments (0)