We know how to use Set and Map in Apex classes, in Javascript ES6 same features are introduced. Now let see how to use Set and Map collections in Lightning web components. These are very useful for handling data in client-side in LWC.
Set:
Same as in apex, Set can hold a list of unique values.Now let's see what are methods it does supports.
// Initilize a set
var fruits = new Set();
console.log(fruits); // op:Set{ }
// add items to set
// add method can add only one iteam at a time, Here i'm trying to add two items but it will take first item only
fruits.add('apple','banana');
console.log(fruits);// op: Set{'apple'}
// add array of items to set
// there is no specific method to add array of items to set. we have to add each one using loop
var todayItems = ['banana', 'Cranberry'];
todayItems.forEach(item => fruits.add(item));
console.log(fruits); // op: Set{'apple', 'banana','Cranberry'}
// check set size
console.log(fruits.size); // op: 3
// find item in Set
console.log(fruits.has('apple')) // op: true
// remove element from Set
console.log(fruits.delete('apple')); // op: true
console.log(fruits)// op: Set{'banana','Cranberry'}
// Display Keys and values
// set have only unique keys or values, so both the methos it will return same result
for(let fruit of fruits.keys()){
console.log(fruit); // op: banana, cranberry
}
for(let fruit of fruits.values()){
console.log(fruit); // op: banana, cranberry
}
// clear the items in set
fruits.clear();
console.log(fruits); // op: set { }
Map:
Same as in apex, Map contains Key Value Pair in Javascript.Now let's see what are the methods it does supports.
// Initilize a map
var fruitsMap = new Map();
// add items to map
fruitsMap.set(001,'apple');
fruitsMap.set(002,'banana');
console.log(fruitsMap); // op: Map {1 => 'apple', 2 => 'banana'}
// check map size
console.log(fruitsMap.size); // op: 2
//
COMMENTS