Map object is used to store data in key-value pairs. It also maintains the order of insertion of elements into the map.
let m = new Map();
m.set("name", "Karl");
Map methods
// DECLARE A MAP OBJECT
let m = new Map();
//INSERT ELEMENT INTO MAP
m.set("name", "Karl");
m.set("age", 25);
console.log(m); // {name:'Krl', age: 25}
// ACCESS ELEMENT OF MAP
m.get("name"); // "Karl"
m.get("age"); // 25
//CHECK IF A KEY EXISTS IN THE MAP
m.has("name"); // true
m.has("phone"); // false
// DELETE AN ELEMENT
m.delete("age"); // true
m.delete("address"); // false => address key doesn't exist on map
// GET THE SIZE OF MAP
m.size(); // output: 2
Iterate map object
There are cases when we need to iterate a map object just like we iterate an array.
We can iterate a map object by:
Using for...of loop.
Using for...each loop
for...of loop
let m = new Map(); m.set(1, "Batman"); m.set(2, "Spiderman"); m.set(3, "Ironman"); for(const [key, val] of m){ console.log(key + " = " + val); } // 1 = Batman // 2 = Spiderman // 3 = Ironman // ITERATING KEYS for(cont key of m.keys()){ console.log(key); } // 1 // 2 // 3 // ITERATING VALUES for(cont val of m.values()){ console.log(val); } // Batman // Spiderman // Ironman
forEach loop
let m = new Map(); m.set(1, "Batman"); m.set(2, "Spiderman"); m.set(3, "Ironman"); m.forEach((val, key) =>{ // Note: key is second parameter. console.log(key + " = " + val); }); // 1 = Batman // 2 = Spiderman // 3 = Ironman
Convert a map into a 2D array
It's super easy to convert a map into a 2D array. We can use a spread operator or Array.from() method.
let m = new Map();
m.set(1, "Batman");
m.set(2, "Spiderman");
m.set(3, "Ironman");
// using spread operator
let 2dArr = [...m];
console.log(2dArr); // [[1, 'Batman'],[2, 'Spiderman'],[3, 'Ironman']]
// using Array.from() method
let 2dArr = Array.from(m);
console.log(2dArr);//[[1, 'Batman'],[2, 'Spiderman'],[3, 'Ironman']]
Convert a 2D array into a map
We need to pass a 2D array as an argument into the map constructor function.
let 2dArr = [[1, 'Batman'],[2, 'Spiderman'],[3, 'Ironman']];
let m = new Map(2dArr);
console.log(m); // {1: 'Batman',2: 'Spiderman',3: 'Ironman',}
I hope you found this article helpful.