š§µ JavaScript Map Object š§µ
ā ļø We will be talking about "Map Object" not "map method".
ā Normal Object ( Before ES6)
- Objects in JavaScript can have only string and symbol as the key.
- There is no particular property to represent the size of the object.
ā Map Object ( ES6)
- Map can hold the key and value of any type. ( string, object, boolean)
- It remembers the original order of the keys.
// Syntax
let map = new Map([iterable]);
ā Important Map methods :
1. Create a new Map object
let john = {name: 'John Doe'},
lily = {name: 'Lily Bush'},
peter = {name: 'Peter Drucker'};
let userRoles = new Map();
2. Add elements to a Map
userRoles.set(john, 'admin');
Since the set method is chainable
userRoles.set(lily, 'editor')
.set(peter, 'subscriber');
3. Initialize Map with an Iterable objects
let userRoles = new Map([
[john, 'admin'],
[lily, 'editor'],
[peter, 'subscriber']
]);
4. Get an element from Map
userRoles.get(john); // admin
userRoles.get(foo); //undefined
5. Check the existence of key
userRoles.has(foo) // false
userRoles.has(lilly) // true
6. Get the number of elements
userRoles.size // 3
7. Iterate over Map keys and values
for (const user of userRoles.keys()) {
console.log(user.name);
}
for (const user of userRoles.values()) {
console.log(user.name);
}
8. Iterate over Map elements
for (const role of userRoles.entries()) {
console.log(`${role[0].name}: ${role[1]}`);
}
9. Convert Map keys or Values to an array
let Arrkeys = [...userRoles.keys()];
console.log(Arrkeys);
10. Delete an element from the Map
userRoles.delete(john)
userRoles.clear() // to delete all entries
ā WeakMap
It is similar to Map except for the keys of WeakMap must be objects.
Map š WeakMap
- Elements of WeakMap can't be iterated.
- WeakMap can't clear all at once.
- WeakMap can't check the size.
Final link: stackblitz.com/edit/js-bo1j63?file=index.js