Maps Iteration In JavaScript: Hello everyone, welcome to the nkcoderz.com website. In this article we will going to discuss about the Maps Iteration In JavaScript.
Maps Iteration In JavaScript
In JavaScript, there are several ways to iterate over the key-value pairs in a Map.
for…of Loop
One way is to use a for...of
loop, like this:
for (let [key, value] of map) {
console.log(key + ": " + value);
}
This will give you an array of [key, value] for each iteration.
Another way is to use the forEach()
method, like this:
forEach() method
map.forEach(function(value, key) {
console.log(key + ": " + value);
});
This will give you the value, key for each iteration.
You can also use the keys()
, values()
and entries()
methods to get an iterator object for the keys, values, or key-value pairs, respectively, and then use a for...of
loop to iterate over them.
For example, to iterate over the keys:
for (let key of map.keys()) {
console.log(key);
}
To iterate over the values:
for (let value of map.values()) {
console.log(value);
}
To iterate over the key-value pairs:
for (let [key, value] of map.entries()) {
console.log(key + ": " + value);
}
You can also use the entries()
method to get an iterator object and use the destructuring assignment to get the key and value separately.
for (let [key, value] of map.entries()) {
console.log(key + ": " + value);
}
You can also use the Object.entries()
method to convert map to array of key-value pairs and then you can use array methods like forEach
, map
, filter
etc to iterate through the map.
Object.entries(map).forEach(([key, value]) => console.log(key, value))
These are some of the ways to iterate over the key-value pairs in a Map in JavaScript. You can use the method that best suits your needs.
Conclusion
If you liked this post Maps Iteration In JavaScript, then please share this with your friends and make sure to bookmark this website for more awesome content.