Sunday 21 October 2018

JavaScript: Exploring Map data structure

JavaScript provides Map data structure, it is used to store the elements in <key, value> pairs and iterate over the elements in insertion order.

How to create a map?
Use the Map constructor to define an instance of Map class.

Syntax
new Map([iterable])
iterable can be an Array or other iterable object whose elements are key-value pairs.

Example 1
HelloWorld.js
var countriesMap = new Map();

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

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

Output
Bahrain : Manama
Cameroon : Yaounde
Norway : Oslo
India : New Delhi

Example 2:
HelloWorld.js
var countries = [["Russia", "Moscow"], ["Spain", "Madrid"]];

var countriesMap = new Map(countries);

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

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


Output
Russia : Moscow
Spain : Madrid
Bahrain : Manama
Cameroon : Yaounde
Norway : Oslo
India : New Delhi




Previous                                                 Next                                                 Home

No comments:

Post a Comment