The Map is the new object type that allows storing collections of key-value pairs. The map is similar to the Object but the main difference is that Map allows keys of any type, even objects or functions. It is easy to get the size of a Map, while it needs more effort to get the size of objects.
Take a look at a simple example on the Map with available methods and properties i.e. set
, get
, has
, delete
, clear
and size
.
let stuff = new Map();
const myStuffFunc = () => 'Hello';
stuff.set(1, 'My Car');
stuff.set(2, 'My House');
stuff.set(3, 'My Airplane');
stuff.set(myStuffFunc, 'Here is a function!');
console.log(`Size of stuff is: ${stuff.size}`); // 4
console.log(stuff.has(1)); // true
console.log(stuff.has(myStuffFunc)); // true
console.log(stuff.has(() => 'test')); // false
console.log(stuff.get(myStuffFunc));
stuff.delete(3);
console.log(stuff.has(3)); // false
stuff.clear();
console.log(`Size of stuff is: ${stuff.size}`); // 0
Assign Object as Key to Map
We can use Object as a key with Map.
let name = { name: "John Doe" };
let stuff = new Map();
stuff.set(name, 123);
console.log( stuff.get(name) ); // 123
Iterating Over Map
It’s easy to iterate over maps by using for...of
.
let myActivities = new Map();
myActivities.set(1, 'Running');
myActivities.set(2, 'Yoga');
myActivities.set(3, 'Boating');
myActivities.set(4, 'Swimming');
for (let [nb, activity] of myActivities) {
console.log(`Activity ${nb} is ${activity}`);
}
// "Activity 1 is Running"
// "Activity 2 is Yoga"
// "Activity 3 is Boating"
// "Activity 4 is Swimming"
We can also iterator over the maps with the use of forEach
. Note, here is the first argument of the callback function is the value and the second argument is the key.
let myActivities = new Map();
myActivities.set(1, 'Running');
myActivities.set(2, 'Yoga');
myActivities.set(3, 'Boating');
myActivities.set(4, 'Swimming');
myActivities.forEach((value, key) => {
console.log(`Activity ${key} is ${value}`);
});
// "Activity 1 is Running"
// "Activity 2 is Yoga"
// "Activity 3 is Boating"
// "Activity 4 is Swimming"
We can also iterator over map for keys and values only by using the keys()
(returns an iterable for keys) and values()
(returns an iterable for values) methods.
let recipeList = new Map([
['cucumber', 500],
['tomatoes', 350],
['onion', 50]
]);
// iterate over keys (vegetables)
for (let vegetable of recipeList.keys()) {
console.log(vegetable); // cucumber, tomatoes, onion
}
// iterate over values (amounts)
for (let amount of recipeList.values()) {
console.log(amount); // 500, 350, 50
}