Javascript Map forEach Method
One of the advantages of the Map
object in Javascript is that it will remember the insertion order of the keys. If you need to iterate over a list of elements and it is important that you do it in the same order they were inserted then Map will allow you to do this.
One way to iterate over all of the elements in a Map
is to get a list of the entries and then use a while
loop to do something with the value.
// Iterate the kv pairs in a Map
let map1 = new Map();
map1.set(1, 'first').set(2, 'second').set(3, 'third');
const iter = map1.entries();
let element = iter.next();
while(!element.done) {
console.log(element.value);
iter.next();
}
Iterating over Map elements using a while loop
In the simple example above we are using the iterator to print out the value of each element to the console. In a real world example this would be replaced by something that acts upon the value of the element.
When you need to iterate over the elements in a Map object and execute some process over the elements you may want to pass the element to another function rather than put all of the logic into a while loop. This is where the forEach()
method can be an effective choice.
The forEach()
method will execute a function once for each key/value pair in the Map
object in the order that they were inserted.
function callback(value, key, map) {
console.log('Key: [' + key + '] = [' + value + ']');
};
let map1 = new Map();
map1.set(1, 'first').set(2, 'second').set(3, 'third');
map1.forEach(callback);
Iterating over Map elements using the forEach() method
In the example using the forEach()
method the value and key are automatically sent to a function. This is a much more clean way of sending each element to a function.
You must be logged in to see the comments. Log in now!