Sometimes, we want to iterate through a map in JavaScript.
In this article, we’ll look at how to iterate through a map in JavaScript.
How to iterate through a map in JavaScript?
To iterate through a map in JavaScript, we can use a for-of loop.
For instance, we write
const myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");
for (const [key, value] of myMap.entries()) {
console.log(key, value);
}
to create a map with the Map
constructor.
Then we call set
to add the key and value of a map entry.
Next, we use the entries
method to return an array with arrays of key-value pairs in myMap
.
And then we use a for-of loop to loop through each entry.
key
is the key of the entry and value
is the value.
Conclusion
To iterate through a map in JavaScript, we can use a for-of loop.