In this article we will learn how to loop through map.
It is very common to loop through map in JavaScript.
Problem
Now we have a problem, which is that we want to loop over the map.
Let's imagine we have a map like this:
// Map
const map = new Map([
['name', 'John'],
['age', 30],
['isMarried', true]
]);
And we want to iterate over this map.
How to solve this problem
As we said before, there is more than one solution to solve this problem:
- Using
forEach
- Using
for ... of
- Iterate over a Map's keys
- Iterate over a Map's values
Iterate over map using forEach
We can use forEach
to iterate over map elements.
Example
// Map
const map = new Map([
['name', 'John'],
['age', 30],
['isMarried', true]
]);
// Iterate using `forEach`
map.forEach(ele => {
console.log(ele);
});
Output
John
30
true
The forEach()
method executes a provided function once for each array element.
Iterate over map using for .. of
We can use for .. of
to iterate over map elements as well.
Example
// Map
const map = new Map([
['name', 'John'],
['age', 30],
['isMarried', true]
]);
// Iterate using `for .. of`
for (let [key, value] of map) {
console.log(key, value);
}
Output
name John
age 30
isMarried true
Iterate over a Map's keys
We can iterate over a map's keys only using keys()
method.
// Map
const map = new Map([
['name', 'John'],
['age', 30],
['isMarried', true]
]);
// Get Keys
const keys = map.keys();
// Iterate over keys
[...keys].forEach(key => {
console.log(key);
})
Output
name
age
isMarried
Iterate over a Map's values
We can iterate over a map's values only using values()
method.
// Map
const map = new Map([
['name', 'John'],
['age', 30],
['isMarried', true]
]);
// Get Values
const values = map.values();
// Iterate over values
[...values].forEach(key => {
console.log(key);
})
Output
John
30
true
Thank you for reading
Thank you for reading my blog. 🚀