Iterate List, Set & Map in LWC Salesforce

Today we will see how to Iterate List, Set & Map in LWC Salesforce. List, sets, and maps are three powerful data structures in LWC that can be used to store, retrieve, and manipulate data. List, Sets, and maps are similar in a way that they are used in collections of data, but they differ in few ways and let’s see their characteristics:


List:

  • List is a collection of elements, such as primitive data types (String, Integer, Date, etc), user defined objects, sObjects, Apex objects or other collections (can be multidimensional up to 5 levels).
  • List index position starts from zero.
  • List allows duplicate values.

Set:

  • Set is a collection of unique, unordered elements.
  • It can contain primitive data types (String, Integer, Date, etc) or sObjects.
  • Set allows unique values.
  • You can create a set in LWC by using the Set() constructor.

 

Map:

  • Map is a collection of key-value pair.
  • Keys can be any primitive data types (String, Integer, Date, etc) while values can include primitives, Apex objects, sObjects and other collections.
  • Map allows duplicate values, but each key must be unique.
  • You can create a map in LWC by using the Map() constructor.

 

  1. List Implementation:

We frequently come across scenario when we have to iterate over list of records say list of contact record and then iterate it in html and display it in a data table. Let’s consider this example and its implementation.

List in LWC can be iterated in 2 ways: For:Each & Iterator

For:Each

<!– forEachDemo.html –>

<template>
    <lightning-card title="Iterate Map in LWC" icon-name="standard:data_mapping">
        <div slot="footer">
        </div>
            <table class="slds-table slds-table_bordered slds-table_cell-buffer slds-table_col-bordered slds-table_striped">
                <thead>
                    <tr class="slds-text-title_caps">
                        <th scope="col">
                            <div title="Key">Name</div>
                        </th>
                        <th scope="col">
                            <div title="Value">Department</div>
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <template for:each={contacts} for:item="map">
                        <tr key={map.Id}>
                            <th scope="col">
                                <div title={map.key}>{map.Name}</div>
                            </th>
                            <th scope="col">
                                <div title={map.value}>{map.Department}</div>
                            </th>
                        </tr>
                    </template>
                </tbody>
            </table>
    </lightning-card>
</template>

 

In this example, we are displaying a list (contacts), which have 3 fields Id, Name and Department.

You can use for:item=”map” to access current item.

/*
* @description: forEach iteration of list in lwc 
* @author: sfdc4u.com
*/
import { LightningElement } from 'lwc';

export default class ForEachDemoLWC extends LightningElement {
    contacts = [
        {
            Id: 1,
            Name: 'Ajit Singh',
            Department: 'Computer Science',
        },
        {
            Id: 2,
            Name: 'Faiz Ahamad',
            Department: 'Computer Science',
        },
        {
            Id: 3,
            Name: 'Amrendra Pratap',
            Department: 'Information Technology',
        },
        {
            Id: 4,
            Name: 'Rakesh Kumar',
            Department: 'M.Sc IT',
        },
        {
            Id: 5,
            Name: 'Ashish Bharti',
            Department: 'Computer Science',
        },
    ];
}

 

Output:

Iterate List, Set & Map in LWC Salesforce

Note: Every item in a list must have a key. When a list changes, the framework uses the key to identify each item so that it can rerender only the item that changed.

In this example we are using <tr key={map.Id}> to assign unique id.

 Iterator

The difference between for:each and iterator is that you can directly access first and last element of the list any time.

Use iteratorName to access these properties:

  1. value—The value of the item in the list. Use this property to access the properties of the array. For example,iteratorName.value.propertyName.
  2. index—The index of the item in the list.
  3. first—A boolean value indicating whether this item is the first item in the list.
  4. last—A boolean value indicating whether this item is the last item in the list.

Let’s take a look at Syntax of Iterator :

<template>
    <lightning-card title="Iterator Demo" icon-name="custom:custom14">
        <ul class="slds-m-around_medium">
            <template iterator:it={contacts}>
                <li key={it.value.Id}>
                    <div if:true={it.first} class="list-first">
                        This is First Item
                    </div>
                     {it.value.Name}, {it.value.Title}
                    <div if:true={it.last} class="list-last">
                         This is Last Item
                    </div>
                </li>
            </template>
        </ul>
    </lightning-card>
</template>

 

  1. Set Implementation

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

set1.add(3);

 

console.log(set1); // { 1, 2,3 }

Remove element from Set :

let set1 = new Set([‘1’, ‘2’, ‘3’, ‘4’]);

set1.delete(‘3’);

console.log(set1); // { ‘1’, ‘2’, ‘4’ }

//clear whole Set

set.clear(); // {}

has(element) from Set :

let set1 = new Set([‘1’, ‘2’, ‘3’, ‘4’]);

console.log(set1.has(‘2’)); // true

console.log(set1.has(‘6’)); // false

Convert Set into an Array :

let set1 = new Set([‘1’, ‘2’, ‘3’, ‘4’,’5’,’6’]);

const arr = […set1];

console.log(arr); //[ ‘1’, ‘2’, ‘3’, ‘4’ , ’5’,’6’]

 Iterate Over a Set :

const set1 = new Set([120, 240, 360]);

set1.forEach((value) => {

console.log(value);

});

 

  1. Map Implementation

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 , “Ajit”], [2 , “Sujit”] ,[3, “Aayush”]]);

 

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 Iteration in LWC’);

map.set(‘type’, ‘blog’);

map.set(‘url’, ‘www.sfdc4u.com’);

map.set(‘writer’, Ajit Singh);

console.log(map);

// output Map(3) {“name” => “Map Iteration in LWC”, “type” => “blog”, “url” => “‘www.sfdc4u.com'”, “writer” => “Ajit Singh”}

//replace writer in map

map.set(‘writer’, ‘Sujit’);

 

 Get values to a Map in :

let map1 = new Map([[1 , “Ajit”], [2 , “Sujit”] ,[3, “Aayush”]]);

console.log(map1 .get(2)); // Sujit

//get size of Map

console.log(‘size of the map is’, map.size());//3

//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 , “Ajit”], [2 , “Sujit”] ,[3, “Aayush”]]);

//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 , “Ajit”], [2 , “Sujit”] ,[3, “Aayush”],[4, “Faiz”]]);

//get all keys

let keys = map1.keys();

console.log(keys); // { 1, 2, 3 ,4}

//get all values

let allValues = map1.values();

console.log(allValues); //{ ‘Ajit’, ‘Sujit’, ‘Himanshu’ }

Iterate Over a Map :

let map1 = new Map([[30 , “Ajit”], [25 , “Sujit”] ,[6, “Aayush”]]);

map1.forEach((value, key) => {

console.log(`${value } is ${key} years old!`);

});

Output:

Ajit is 30 years old!

Sujit is 25 years old!

Aayush is 6 years old!

 

Convert Map into an Array :

let map1 = new Map([[1 , “Ajit”], [2 , “Sujit”] ,[3, “Aayush”]]);

console.log(Array.from(map1)); //  [ [ 1, ‘Ajit’ ], [ 2, ‘Sujit’ ], [ 3, ‘Aayush’ ] ]

Also Read : Best Practices in LWC

Leave a Comment