Description

For sane people ES6 comes with a half assed “solution” handy data structure called Map which prevents the diy shenanigans below.

Syntax

Basic operation

Single entries

const map = new Map();
const KEY = {};
 
map.set(KEY, 123);
console.log(map.get(KEY)); // 123
 
console.log(map.has(KEY)); // true
 
map.delete(KEY);
console.log(map.has(KEY)); // false

Array

const map = new Map([
    [ 1, 'one' ],
    [ 2, 'two' ],
    [ 3, 'three' ],
]);

Iteration

Keys

const map = new Map([
    [false, 'no'],
    [true,  'yes'],
]);
 
for (const key of map.keys()) {
    console.log(key);
}

Values

const map = new Map([
    [false, 'no'],
    [true,  'yes'],
]);
 
for (const value of map.values()) {
    console.log(value);
}

Entries

const map = new Map([
  [false, "no"],
  [true, "yes"],
]);
 
for (const entry of map.entries()) {
  console.log(entry[0], entry[1]);
}

Converting to Arrays

The spread operator (…) can turn an iterable into an Array

const map = new Map().set(false, 'no').set(true, 'yes');
console.log([...map.keys()]) // false, true
const map = new Map().set(false, 'no').set(true, 'yes');
console.log([...map])