Javascript-Map
The Map object holds key-value pairs and recalls the original insertion order of the keys. Any values both primitive values and objects may be used as either a key or a value.
This Map object iterates elements in insertion order wise. A for…of loop written an array of [key, value] for every iteration.
Syntax:
array.map(function(currentValue, index, arr), thisValue)
- map() does not run the function for array elements without values.
Note: this map() method does not change the original array.
Methods and properties are:
- new Map() – creates the map.
- map.set(key, value) – Stores the values by the keys.
- map.get(key) – returns the value by the key, undefined if the key does not exist in the map.
- map.has(key) – 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.
For instance:
<!DOCTYPE html>
<script>
"use strict";globalThis.__codeBoxId = "10tnj9teb5";
let map = new Map();
map.set('1', 'str1'); // a string key
map.set(1, 'num1'); // a numeric key
map.set(true, 'bool1'); // a boolean key
// remember the regular Object? it would convert keys to string
// Map keeps the type, so these two are different:
alert( map.get(1) ); // 'num1'
alert( map.get('1') ); // 'str1'
alert( map.size ); // 3
</script>
Map can also use objects as keys:
<!DOCTYPE html>
<script>
"use strict";globalThis.__codeBoxId = "57p59bsvvb";
let john = { name: "John" };
// for every user, let's store their visits count
let visitsCountMap = new Map();
// john is the key for the map
visitsCountMap.set(john, 123);
alert( visitsCountMap.get(john) ); // 123
</script>
Iteration over Map:
There are 3 methods:
- keys() – iterable for keys,
- values() – iterable for values,
- entries() – iterable for entries [key, value]. It’s used by default in for..of.
For instance:
<!DOCTYPE html>
<script>
"use strict";globalThis.__codeBoxId = "df4ipdfkim";
let recipeMap = new Map([
['cucumber', 500],
['tomatoes', 350],
['onion', 50]
]);
// iterate over keys (vegetables)
for (let vegetable of recipeMap.keys()) {
alert(vegetable); // cucumber, tomatoes, onion
}
// iterate over values (amounts)
for (let amount of recipeMap.values()) {
alert(amount); // 500, 350, 50
}
// iterate over [key, value] entries
for (let entry of recipeMap) { // the same as of recipeMap.entries()
alert(entry); // cucumber,500 (and so on)
}
</script>