Notes

[ES2015] Map object

Edit on GitHub

JavaScript

Map

The Map object is a simple key/value map. Any value (both objects and primitive values) may be used as either a key or a value.

You set and get values to/from a Map.

 1'use strict';
 2
 3let classroom = new Map();
 4
 5let stevenJ = { name: 'Steven', age: 22 },
 6    sarah = { name: 'Sarah', age: 23 },
 7    stevenS = { name: 'Steven', age: 22 };
 8
 9classroom.set('stevenJ', stevenJ)
10classroom.set('sarah', sarah)
11classroom.set('stevenS', stevenS)
12
13console.info('classroom size: ', classroom.size) // classroom size: 3
14
15if (classroom.has('stevenJ')) console.log('stevenJ is in the classroom') // stevenJ is in the classroom
16
17console.log('sarah', classroom.get('sarah')) // sarah: { name: 'Sarah', age: 23 } 
18classroom.delete('sarah')
19console.log('sarah:', classroom.get('sarah')) // sarah: undefined
20
21for (let student of classroom) {
22  console.log(`${student[0]}: ${student[1].name} is ${student[1].age} years old`)
23}
24// stevenJ: Steven is 22 years old            
25// stevenS: Steven is 22 years old
26
27console.info('classroom size: ', classroom.size) // classroom size: 2
28classroom.clear()
29console.info('classroom size: ', classroom.size) // classroom size: 0

To empty a Set or Map object of all stored values, you can use the clear() method.

Map vs. Set

Related