Iterate map collection using entries() method in Javascript
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.
Syntax
 1 <map>.entries() // returns MapIterator {}
map : A map object for which converted to iterator using entries() method
entries() method
 1 let map = new Map();
 2 
 3 // adding elements in map
 4 map.set('a', 10); // returns - Map(1) {'a' => 10}
 5 map.set('b', 20); // returns - Map(2) {'a' => 10, 'b' => 20}
 6 
 7 map.entries(); // entries() function returns MapIterator object
 8 
 9 // convert to iterator and print elements
 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.
Output
 1 a = 10
 2 b = 20

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 // print updated map
 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.
Output
 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 // print updated map
 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.
Output
 1 Map(2) { 'a' => 10, 'c' => 30 }
Privacy Policy
Terms of Service
Disclaimer
Contact us
About us