Monday, April 16, 2018

Iteration Map

Consider I am passing an array to the map like below,


// array of [key, value] pairs
let map = new Map([
  ['1',  'stringOne'],
  [1,    'number1'],
  [true, 'booleanTrue']
]);

Object.entries(obj) is an inbuilt method  which returns an array of key/value pairs for an object with same format.

We can an initialize a map from an object like below,


let map = new Map(Object.entries({
  name: "Tester",
  age: 30
}));

Here, Object.entries returns the array of key-value pairs.

Output:
 [ ["name","Tester"], ["age", 30] ].

Iterate on Map:

There are 3 methods, we can use..

map.keys() – returns an iterable for keys,
map.values() – returns an iterable for values,
map.entries() – returns an iterable for entries [key, value] and it is used by default in for..of.

Example I :



let sportsMap = new Map([
  ['Cricket', 500],
  ['Football', 350],
  ['WWE',    50]
]);

// iterate over keys (vegetables)
for (let sport of sportsMap.keys()) {
  alert(sport); // cricket, Football, WWE
}

// iterate over values (amounts)
for (let fee of sportsMap.values()) {
  alert(fee); // 500, 350, 50
}

// iterate over [key, value] entries
for (let entry of sportsMap) { // the same as of recipeMap.entries()
  alert(entry); // cricket,500 (and so on)
}

Note: Map preserves this insertion order


ForEach with ES6 :

Map has a built-in forEach method, similar to Array...

Example II


sportsMap.forEach( (value, key, map) => {
  alert(`${key}: ${value}`); // cricket: 500 etc
});







No comments:

Post a Comment