Useful JavaScript methods in LWC Part -2

by Rijwan Mohmmed
useful-javascript-methods-in-lwc-part-2.

Hello folks, today we will discuss some Useful JavaScript methods in LWC Salesforce Part-2. In this blog, we will discuss Map and Set in LWC Js.

Map in LWC JS: We use Map to store key value.

import { LightningElement } from 'lwc';
export default class LWCUsefulMethod 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 in LWC JS: We use Set in JS for store unique values.

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);  
        });
    }
}

Reference :

  1. Set
What’s your Reaction?
+1
1
+1
0
+1
1
+1
0
+1
0
+1
0

You may also like

Leave a Comment