Map

Maps are a store for key / value pairs. Key and value could be a primitives or object references.

Let’s create a map:

let map = new Map(),

val2 = 'val2',

val3 = {

key: 'value'

}; map.set(0, 'val1');

map.set('1', val2);

map.set({ key: 2 }, val3); console.log(map); // Map {0 => 'val1', '1' => 'val2', Object {key: 2} => Object {key: 'value'}}

We can also use a constructor to create the sam map, based on array param passed to the constructor:

let map,

val2 = 'val2',

val3 = {

key: 'value'

}; map = new Map([[0, 'val1'], ['1', val2], [{ key: 2 }, val3]]); console.log(map); // Map {0 => 'val1', '1' => 'val2', Object {key: 2} => Object {key: 'value'}}

To get a value by using a key, we have to use a get() method to do it (surprising):

let map = new Map(),

val2 = 'val2',

val3 = {

key: 'value'

}; map.set(0, 'val1');

map.set('1', val2);

map.set({ key: 2 }, val3); console.log(map.get('1')); // val2

To iterate over the map collection, we can use built-in forEach method or use new for..of structure: