Javascript Map Type

Introduction

Javascript Map handles key/value pair structure.

An empty Map is instantiated with the new keyword:

const m = new Map(); 

The constructor optionally accepts an iterable object, expecting it to contain key/value pair arrays.

Initialize map with nested arrays


const m1 = new Map([//from ww  w  . j av  a  2  s. c o m
    ["key1", "val1"],
    ["key2", "val2"],
    ["key3", "val3"]
]);
console.log(m1.size); // 3 

Initialize map with custom-defined iterator

const m2 = new Map({//  w w w . j  av a 2s. c  om
    [Symbol.iterator]: function*() {
        yield ["key1", "val1"];
        yield ["key2", "val2"];
        yield ["key3", "val3"];
    }
});
console.log(m2.size); // 3 

Map expects values to be key/value whether they are provided or not

const m3 = new Map([/*from ww w. j a  v  a 2 s.  com*/
    []
]);
console.log(m3.has(undefined)); // true 
console.log(m3.get(undefined)); // undefined 

Using the Map object

let myMap = new Map();

let keyString = 'a string';
let keyObj    = {};
let keyFunc   = function() {};

myMap.set(keyString, "'a string'");
myMap.set(keyObj, 'keyObj');
myMap.set(keyFunc, 'keyFunc');

console.log(myMap.size);// 3

// getting the values
let a = myMap.get(keyString);
console.log(a);/*from w w w. ja  va  2 s .  c o m*/
a = myMap.get(keyObj);   
console.log(a);
a = myMap.get(keyFunc);      
console.log(a);

a = myMap.get('a string');
console.log(a);
                        
a = myMap.get({});
console.log(a);
a = myMap.get(function() {});
console.log(a);

Iterating Map with for..of

let myMap = new Map();
myMap.set(0, 'zero');
myMap.set(1, 'one');

for (let [key, value] of myMap) {
  console.log(key + ' = ' + value)
}

for (let key of myMap.keys()) {
  console.log(key)/*from   ww  w .j  a  va 2 s.  c om*/
}

for (let value of myMap.values()) {
  console.log(value)
}

for (let [key, value] of myMap.entries()) {
  console.log(key + ' = ' + value)
}

Iterating Map with forEach()

let myMap = new Map();
myMap.set(0, 'zero');
myMap.set(1, 'one');

myMap.forEach(function(value, key) {
  console.log(key + ' = ' + value)
})



PreviousNext

Related