A JavaScript has Map collection which stores value in the form of key and value. It allows at most one value per key where key should be unique (no duplicate key). If new value added with duplicate key, it will replace existing element with the new element.
1
2 let <variable> = new Map();
3
4
5 let <variable> = new Map([
6 [<key>, <value>],
7 [<key>, <value>]]);
variable : A map variable stores key and value
key : A key which uniquely identifies each element of map
value : A value for each map element key
1
2 let map = new Map();
3
4
5 let map = new Map([
6 ['a', 10],
7 ['b', 20]]);
8
9
In the above example, we have created map using Map class constructor without initial value. An element added into the map using set() method. In the second example, we have created map with initial elements. It expects initial value as an array. An each element of a map can be specify by an array. The first element array contain key and second element will be a value.
Add entry in map
1
2 let map = new Map();
3
4
5 map.set(10, "ten");
6 map.set(20, "twenty");
7
8
9 console.log(map);
In the above example, a map object is declared using constructor method. A new element is added by calling a set() method and passing a key and value. A map object is print using console log() method that prints updated map object.
1 Map(2) { 10 => 'ten', 20 => 'twenty' }
Iterate map object using forEach()
Iterate map object using forEach()
1
2 let map = new Map();
3
4 map.set(10, "ten");
5 map.set(20, "twenty");
6
7 map.forEach((value, key, map) => {
8 console.log(value, key, map);
9 });
In the above example, a map object is created and adding an entries. A forEach() function is called by passing a callback function that receives three parameters, value, key and map object. A key and map object is optional. A callback function prints all three values using console log() method.
1 ten 10 Map(2) { 10 => 'ten', 20 => 'twenty' }
2 twenty 20 Map(2) { 10 => 'ten', 20 => 'twenty' }
Iterate map using for...of
Iterate map using for...of
1
2 let map = new Map();
3
4 map.set(10, "ten");
5 map.set(20, "twenty");
6
7 for(entry of map) {
8 console.log(entry);
9 }
In the above example, a map object iterated using for...of loop that iterate entry in each iteration. An entry includes an array that includes two element key and value. An entry object is print that prints an array using console log() method.
1 [ 10, 'ten' ]
2 [ 20, 'twenty' ]
Related options for your search