Set & Map in LWC Salesforce

by Rijwan Mohmmed
Set-map-in-lwc-salesforce-techdicer

Hello friends, today we will discuss Set & Map in LWC Salesforce. In LWC (Lightning Web Components), sets and maps are two powerful data structures that can be used to store, retrieve, and manipulate data. Sets and maps are similar in that they are both collections of data, but they have some important differences as well.

Also, check this: Package.xml to Retrieve All Metadata from Salesforce Org

Key Highlights :

  1. A Set is an unordered collection of unique elements.
  2. You can create a set in LWC by using the Set() constructor.
  3. A Map is an ordered collection of key-value pairs.
  4. You can create a map in LWC by using the Map() constructor.
  5. Map allows keys of any type.

Code :

Map collection in LWC:

The map is a collection of key-value pairs where the key can be of any type. Map remembers the original order in which the elements were added to it, which means data can be retrieved in the same order it was inserted in.

//initilize the map collection in LWC JS
const map = new Map();

//We can also initilize the map with existing data
let map1 = new Map([[1 , "Ankit"], [2 , "Rijwan"] ,[3, "Himanshu"]]);

# Add values to a Map in :
Use the set(key, value) method to add key value in the map

// create a map
const map = new Map();

// Add values to the map
map.set('name', 'Map in LWC');
map.set('type', 'blog');
map.set('writer', 'Rijwan');
console.log(map);
// output Map(3) {"name" => "Map in LWC", "type" => "blog", "writer" => "Rijwan"}

//replace writer in map
map.set('writer', 'Himanshu');

# Get values to a Map in :

let map1 = new Map([[1 , "Ankit"], [2 , "Rijwan"] ,[3, "Himanshu"]]);
console.log(map1 .get(2)); // Rijwan
//get size of Map
console.log('size of the map is', map.size);
//Check whether map contains key. ==> has(key)
if(map1.has(2)){
    console.log('key 2 is present'); // key 2 is present
}

# Remove values from a Map :

let map1 = new Map([[1 , "Ankit"], [2 , "Rijwan"] ,[3, "Himanshu"]]);
//remove single key value
map1.delete(1); // delete(key) - delete given key from map

//clear whole map
map1.clear(); //clear() - clear whole map 

# Get/ print all keys & values from a Map :

let map1 = new Map([[1 , "Ankit"], [2 , "Rijwan"] ,[3, "Himanshu"]]);
//get all keys 
let keys = map1.keys();
console.log(keys); // { 1, 2, 3 }

//get all values 
let allValues = map1.values();
console.log(allValues); //{ 'Ankit', 'Rijwan', 'Himanshu' }

# Iterate Over a Map :

let map1 = new Map([[1 , "Ankit"], [2 , "Rijwan"] ,[3, "Himanshu"]]);
map1.forEach((value, key) => {
    console.log(`${key} is ${value} years old!`);
});

# Convert Map into an Array :

let map1 = new Map([[1 , "Ankit"], [2 , "Rijwan"] ,[3, "Himanshu"]]);
console.log(Array.from(map1)); //[ [ 'milk', 200 ], [ 'tea', 300 ], [ 'coffee', 500 ] ]

mapInLWC.JS :

import { LightningElement } from 'lwc';
export default class LWCMapCollection extends LightningElement {

    handleMapInLWC(){
      //Define a map in LWC
      let map1 = new Map([[1 , "Ankit"], [2 , "Rijwan"] ,[3, "Himanshu"]]);
      //Check whether map contains key. ==> has(key)
      if(map1.has(2)){
         console.log('key 2 is present');
      }

      // fetch value by key ==> map1.get(key)
     console.log(map1.get(1));

    //set key and value in map ==> set(key,value)
    map1.set(4, "Sachin");

    //delete(key) - delete given key from map.
    map1.delete(4);

    //clear() - clear whole map.
    map1.clear();

   //keys() ==> print all keys
   console.log(map1.keys());

   // print all values of map =>values()
    console.log(map1.values());

   //loop on map
  map1.forEach((value, key, map)=>{
    console.log('Key -> ' + key + ' value -> ' + value);
  });
}
}

Set collection in LWC :

A Set is a collection of unique elements that can be of any type. A Set is also an ordered collection of elements, which means that elements will be retrieved in the same order that they were inserted.

# Add element in Set :

let set1 = new Set();
set1.add(1);
set1.add(2);
set1.add(2);
console.log(set1); // { 1, 2 }

#  Remove element from Set :

let set1 = new Set(['1', '2', '3', '4']);
set1.delete('2');
console.log(set1); // { '1', '3', '4' }
//clear whole Set
set.clear(); // {}

# has(element) from Set :

let set1 = new Set(['1', '2', '3', '4']);
console.log(saladSet.has('2')); // true
console.log(saladSet.has('6')); // false

# Convert Set into an Array :

let set1 = new Set(['1', '2', '3', '4']);
const arr = [...set1];
console.log(arr); //[ '1', '2', '3', '4' ]

# Iterate Over a Set :

const set1 = new Set([360, 567, 101]);
set1.forEach((value) => {
     console.log(value);
});

SetInLWC.JS :

import { LightningElement } from 'lwc';
export default class LWCUsefulMethod extends LightningElement {
 
    handlSetInLWC(){
        //add unique values in array use set()
        let set1 = new Set();
        set1.add(1);
        set1.add(2);
        set1.add(2);
        set1.add(3);
        set1.add(3);

        //loop on set
        set1.forEach(function(value, valueAgain, set){
            console.log(value);  
        });
        set1.delete('2');
        console.log(saladSet.has(1)); // true
        console.log(saladSet.has(1)); // false
        set1.clear(); //clear whole set collection
    }
}

Output :

Reference :

  1. Set & Map in LWC
  2. Set
What’s your Reaction?
+1
6
+1
2
+1
0
+1
1
+1
2
+1
1

You may also like

Leave a Comment