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}`);
}
Output:
Cricket is sport
Apple is fruit
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);
});
Output:
1 Monday
2 Tuesday
3 Wednesday
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);
}
Output:
a
b
d
4. Using Array.from()
and forEach()
- Converts
Map.entries()
to an array and iterates usingforEach()
.
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
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);
}
Output:
animal
fruit
vehicle
Each method provides flexibility depending on whether you need keys, values, or key-value pairs. 🎯
Top comments (0)