Map in JavaScript
1. Define a map in LWC and Aura Component -
let map1 = new Map([[1 , "Saurabh"], [2 , "Supriya"] ,[3, "Yuvraj"]]);
console.log(map1.get(1)); // print Saurabh
2. get(key) - fetch value by key
console.log(map1.get(1)); // print Saurabh
3. set(key,value) - adds key and value to map.
map1.set(4, "ABCD");
4. has(key) - Check whether map contains key.
if(map1.has(3))
{
console.log('key 3 is present');
}
5. delete(key) - delete given key from map.
6. clear() - clear whole map.
7. keys() - This method return all keys in a map.
console.log(map1.keys()); // print 1,2,3,4
8. values() - This method return all values in a map.
console.log(map1.values()); // print Saurabh, Supriya, Yuvraj, ABCD
9. forEach() - This function executes each key/value pair in the map. you can give a callback function to perform. Syntax - map1.forEach(callback[, thisArgument]);
This callback function can have 3 params value, key and map on which forEach is called.
map1.forEach(function(value, key, map)
{
console.log('Key -> ' + key + ' value -> ' + value);
});
Set in JavaScript
10. Create new Set -
let set1= new Set();
set1.add(1);
set1.add(2);
set1.add(3);
let set2 = new Set();
let john = { name: "John" };
let pete = { name: "Pete" };
let mary = { name: "Mary" };
// visits, some users come multiple times
set2.add(john);
set2.add(pete);
set2.add(mary);
set2.add(mary);
set2.add(mary);
11. forEach for Set - The forEach method for set accept 3 params value, valueagain, set.
valueagain is the same value. Yes, it is the duplicate parameter. This is deliberately done to be in sync with forEach function of Map or Array.
set1.forEach(function(value, valueAgain, set){
alert(value);
});
12. keys() - return all keys in set.
13. value() - same as keys().