Javascript map ¶
Contents
Définition en français ¶
L’objet Map représente un dictionnaire, autrement dit une carte de clés/valeurs.
N’importe quelle valeur valable en JavaScript (que ce soit les objets ou les valeurs de types primitifs) peut être utilisée comme clé ou comme valeur.
L’ordre d’insertion des clés est mémorisé dans l’objet et les boucles sur les Map parcourent les clés dans cet ordre.
https://flaviocopes.com ¶
Before ES6 ¶
ECMAScript 6 (also called ES2015) introduced the Map data structure to the JavaScript world, along with Set
Before its introduction, people generally used objects as maps, by associating some object or value to a specific key value:
1 const car = {}
2 car['color'] = 'red'
3 car.owner = 'Flavio'
4 console.log(car['color']) //red
5 console.log(car.color) //red
6 console.log(car.owner) //Flavio
7 console.log(car['owner']) //Flavio
Enter Map ¶
ES6 introduced the Map data structure, providing us a proper tool to handle this kind of data organization.
A Map is initialized by calling:
1 const m = new Map()
Add items to a Map
You can add items to the map by using the set method:
1 m.set('color', 'red')
2 m.set('age', 2)
Initialize a map with values ¶
You can initialize a map with a set of values:
1 const m = new Map([['color', 'red'], ['owner', 'Flavio'], ['age', 2]])
https://javascript.info/map-set ¶
See also
Map is a collection of keyed data items, just like an Object.
But the main difference is that Map allows keys of any type.
Methods and properties are:
-
new Map() – creates the map.
-
map.set(key, value) – stores the value by the key.
-
map.get(key) – returns the value by the key, undefined if key doesn’t exist in map.
-
map.has(key) – returns true if the key exists, false otherwise.
-
map.delete(key) – removes the value by the key.
-
map.clear() – removes everything from the map.
-
map.size – returns the current element count.
Example ¶
1 let recipeMap = new Map([
2 ['cucumber', 500],
3 ['tomatoes', 350],
4 ['onion', 50]
5 ]);
6
7 // iterate over keys (vegetables)
8 for (let vegetable of recipeMap.keys()) {
9 alert(vegetable); // cucumber, tomatoes, onion
10 }
11
12 // iterate over values (amounts)
13 for (let amount of recipeMap.values()) {
14 alert(amount); // 500, 350, 50
15 }
16
17 // iterate over [key, value] entries
18 for (let entry of recipeMap) { // the same as of recipeMap.entries()
19 alert(entry); // cucumber,500 (and so on)
20 }
The insertion order is used ¶
Note
The iteration goes in the same order as the values were inserted. Map preserves this order, unlike a regular Object.
Object.fromEntries: Object from Map ¶
We’ve just seen how to create Map from a plain object with Object.entries(obj).
There’s Object.fromEntries method that does the reverse: given an array of [key, value] pairs, it creates an object from them:
1 let prices = Object.fromEntries([
2 ['banana', 1],
3 ['orange', 2],
4 ['meat', 4]
5 ]);
6
7 // now prices = { banana: 1, orange: 2, meat: 4 }
8
9 alert(prices.orange); // 2