Sunday, 21 October 2018

JavaScript: Map.prototype.entries(): Get all the entries in map

Map.prototype.entries()
This method returns an array of [key, value] entries in the map.

For example, below snippet iterate over the elements of a map.

  var entries = map.entries();
 
  for (var [country, capital] of entries) {
    console.log(country + ' : ' + capital);
  }

HelloWorld.js
function printMap(map){
  console.log("***************************");
  console.log("Total elements in countriesMap are : " + map.size);
  
  var entries = map.entries();
  
  for (var [country, capital] of entries) {
    console.log(country + ' : ' + capital);
  }
  console.log("***************************");
}

var countriesMap = new Map();

countriesMap.set("Bahrain", "Manama");
countriesMap.set("Cameroon", "Yaounde");
countriesMap.set("Norway", "Oslo");
countriesMap.set("India", "New Delhi");
countriesMap.set("Russia", "Moscow");
countriesMap.set("Spain", "Madrid");

printMap(countriesMap);

console.log("\nDeleting the keys 'Spain', 'Cameroon', 'India'\n");

countriesMap.delete("Spain");
countriesMap.delete("Cameroon");
countriesMap.delete("India");

printMap(countriesMap);


Output

***************************
Total elements in countriesMap are : 6
Bahrain : Manama
Cameroon : Yaounde
Norway : Oslo
India : New Delhi
Russia : Moscow
Spain : Madrid
***************************




Previous                                                 Next                                                 Home

No comments:

Post a Comment