-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmap.js
More file actions
69 lines (51 loc) · 1.98 KB
/
map.js
File metadata and controls
69 lines (51 loc) · 1.98 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
const map = new Map();
map.set(1, 'one');
map.set(2, 'two');
map.set('ok', 234, 45); // third arg is skipped
// => Map { 1 => 'one', 2 => 'two', 'ok' => 234 }
// Regular Object converts keys to string but Map keeps the type
const john = { name: 'John' };
const visitsMap = new Map();
visitsMap.set({ name: 'Bill', age: 33 }, 23)
.set('Sam', 65)
.set(john, 23)
.set(john, 34); // gets overwritten
const visitor = visitsMap.get('Sam'); // 65
// Using objects as keys is one of most notable and important Map features. !!!
// For string keys, Object can be fine, but not for object keys.
// For looping over a map, there are 4 methods: !!!
const recipeMap = new Map([
['cucumber', 500],
['tomatoes', 350],
['onion', 50]
]);
// iterate over keys (vegetables)
for (const vegetable of recipeMap.keys()) {
console.log(vegetable); // cucumber, tomatoes, onion
}
// iterate over values (amounts)
for (const amount of recipeMap.values()) {
console.log(amount); // 500, 350, 50
}
// iterate over [key, value] entries
for (const entry of recipeMap) { // the same as of recipeMap.entries()
console.log(entry); // cucumber, 500 (and so on)
}
// Besides that, Map has a built-in forEach method, similar to Array:
// runs the function for each (key, value) pair
recipeMap.forEach((value, key, map) => {
// console.log(map); // logs entire Map
console.log(`${key}: ${value}`); // cucumber: 500, tomatoes: 350 ...
});
// The iteration goes in the same order as the values were inserted.
// Map preserves this order, unlike a regular Object. !!!
const saraObj = { name: 'Sara', job: 'coder' };
const saraEntries = Object.entries(saraObj);
// => [ [ 'name', 'Sara' ], [ 'job', 'coder' ] ]
// Convert object to Map:
const mapSara = new Map(saraEntries);
console.log('mapSara', mapSara);
// => Map { 'name' => 'Sara', 'job' => 'coder' }
// Convers from entries to object:
const prices = Object.fromEntries([['banana', 1], ['orange', 2]]); // needs nodejs v.12.4+ !!!
// => { banana: 1, orange: 2 }