Code
Example - Creating a new map and adding objects
//ES6 Maps and Sets - Create a map and add items
// general flow create a map, assign a key in which you can retrieve objects
let cardAce = {
name : 'Ace of Spades'
};
let cardKing = {
name : 'King of Clubs'
};
let deck = new Map(); // Create a new Map object
let deckAlt = new Map([['as', cardAce], ['kc', cardKing]]); // Alternative Syntax to create our deck map
deck.set('as', cardAce); //Set new key/value in our deck map
deck.set('kc', cardKing); //Set new key/value in our deck map
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Managing map items
//ES6 Maps and Sets - Retrieving and Managing values within the map
let cardAce = {
name : 'Ace of Spades'
};
let cardKing = {
name : 'King of Clubs'
};
let deck = new Map();
deck.set('as', cardAce);
deck.set('kc', cardKing);
console.log(deck.size); //access size of map
console.log(deck.get('as')); //get(keyvalue) - retrieves value from map by key
console.log(deck.delete('as')); //delete(keyvalue) - deletes value from map by key
console.log(deck.clear()); //clear() - removes all key/value pairs from the map
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Looping through maps
//ES6 Maps and Sets - Looping through maps
let cardAce = {
name : 'Ace of Spades'
};
let cardKing = {
name : 'King of Clubs'
};
let deck = new Map();
deck.set('as', cardAce);
deck.set('kc', cardKing);
//Loops through map and returns the keys
for (key of deck.keys()) {
console.log(key);
}
//Loops through map and returns the values
for (value of deck.values()) {
console.log(value);
}
//Loops through map and returns the key/value pairs as an array - Method #1
for (entry of deck.entries()) {
console.log(entry);
}
//Loops through map and returns the key/value pairs as an array - Method #2
for (entry of deck) {
console.log(entry);
}
//You can also override looping through your map using iterators and next() because it is an array
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39