Maps in ES6

Description

Working with maps in ES6
James Drummond
Note by James Drummond, updated more than 1 year ago
James Drummond
Created by James Drummond almost 9 years ago
7
0

Resource summary

Page 1

> let map = new Map(); > map.set('foo', 123); > map.get('foo') 123 > map.has('foo') true > map.delete('foo') true > map.has('foo') false

let map = new Map([ [ 1, 'one' ], [ 2, 'two' ], [ 3, 'three' ], // trailing comma is ignored ]);Also:let map = new Map() .set(1, 'one') .set(2, 'two') .set(3, 'three');

Any value can be a key, even an object: let map = new Map(); const KEY1 = {}; map.set(KEY1, 'hello'); console.log(map.get(KEY1)); // hello const KEY2 = {}; map.set(KEY2, 'world'); console.log(map.get(KEY2)); // world

Iterate using for and let:for (let value of map.values()) { console.log(value); } Destructuring enables you to access the keys and values directly: for (let [key, value] of map.entries()) { console.log(key, value); } Or you can just say: for (let [key, value] of map) { console.log(key, value); }

The Spread operator (...)The spread operator (...) turns an iterable into the arguments of a function or parameter call.> let arr = [2, 11, -1]; > Math.max(...arr) 11 Spread also turns an iterable into the elements of an array. That lets us convert the result of Map.prototype.keys() (an iterable) into an array: let map = new Map([ [1, 'one'], [2, 'two'], [3, 'three'], ]); let arr = [...map.keys()]; // [1, 2, 3]

Show full summary Hide full summary

Similar

Sets in ES6
James Drummond
Arrow functions
James Drummond
Quiz - Object Oriented Javascript
arunram.krish
Examen Fundamentos Basicos de Programación
Jose Valderrama0721
Test I. Introduction to web technologies
Angel Martínez Rodriguez
JavaScript Fundamentals
Andrew Watters
Front-End Web Development
Chanthy Ngin
Javascript - Quiz - Jan 2016
arunram.krish
OpenSource Programming
Faheem Ahmed
Javascript basics
James Drummond
jQuery Basics functions and method
Victor Bini