A Map object is iterated by converting Map object into iterator object. An iterator can be converted from Map using entries() method. It returns a new iterator object containing all the elements in a map object which can iterated using for loop.
map : A map object for which converted to iterator using entries() method
1 let map = new Map();
2
3
4 map.set('a', 10);
5 map.set('b', 20);
6
7 map.entries();
8
9
10 for(let ele of map.entries()) {
11 console.log(ele[0] + ' = ' + ele[1]);
12 }
In the above example, we have define map object using Map class constructor. A elements are added using set() method. A map entries() function returns MapIterator object which is iterated using for-of loop and printed key and value on console.
Delete entry while iterating
Delete entry while iterating
1 let map = new Map([
2 ['a', 10],
3 ['b', 20],
4 ['c', 30]]);
5
6 for(entry of map.entries()) {
7 if(entry[0] == 'b') {
8 map.delete(entry[0]);
9 }
10 }
11
12 console.log(map);
In the above example, a map is declared with three elements and iterated using for...of loop. A map entries() method called that returns an iterator object that allows to update or modify map object while iterating map entries. If current entry key is b, an entry will be deleted from map. An updated map prints that does not includes entry with key b.
1 Map(2) { 'a' => 10, 'c' => 30 }
Delete entry using keys()
Delete entry using keys()
1 let map = new Map([
2 ['a', 10],
3 ['b', 20],
4 ['c', 30]]);
5
6 for(key of map.keys()) {
7 if(key == 'b') {
8 map.delete(key);
9 }
10 }
11
12 console.log(map);
In the above example, a map method keys() called that returns an iterator object and includes keys. A map object keys are iterated using for...of loop and if key match with b it removes an entry from map. An updated map that does not includes entry with key b.
1 Map(2) { 'a' => 10, 'c' => 30 }
Related options for your search