Iterate Map in Lightning Web Components

Lightning Web Components (LWC) is a new development approach provided by Salesforce. If you are still thinking where to start studying about Lightning Web Component (LWC) then you can start from here. In the end I have added link of other post which you can check to get the hands-on experience with LWC. Today we will check how we can iterate map in Lightning Web Components (LWC) .

There is a common question in Lightning and that is How to iterate map in Lightning. This is a very common requirement. But if you are planning to use map with LWC then the same question How to iterate map in Lightning Web Component (LWC) comes.

The approach which we have used in Lightning also works in LWC. So I have modify that code and made that Lightning Web Components (LWC) compatible. I have used Opportunity, Account records to make a working demo.

Iterate map in Lightning Web Components (LWC)  Salesforce

Now we will check the code part. Code is quite similar of what we have done in Lightning. We will take help of JavaScript to convert map into array of objects and then will iterate that.

lwcMapIteration.html

<template>
    <lightning-card>
        <h3 slot="title">
            <lightning-icon icon-name="utility:connected_apps" size="small"></lightning-icon>
            Iterate Map in Lightning Web Components
        </h3>
        <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">Opportunity Name (Key)</div>
                        </th>
                        <th scope="col">
                            <div title="Value">Account Name (Value)</div>
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <template for:each={mapData} for:item="mapKey">
                        <tr key={mapKey.key}>
                            <th scope="col">
                                <div title={mapKey.key}>{mapKey.key}</div>
                            </th>
                            <th scope="col">
                                <div title={mapKey.value}>{mapKey.value}</div>
                            </th>
                        </tr>
                    </template>
                </tbody>
            </table>
    </lightning-card>
</template>

lwcMapIteration.js

import { LightningElement, wire, track } from 'lwc';
import fetchMapData from '@salesforce/apex/LwcMapIterationController.fetchMapData';

export default class LwcMapIteration extends LightningElement {
    @track mapData= [];

    @wire(fetchMapData)
    wiredResult(result) { 
        if (result.data) {
            //mapData = [];
            var conts = result.data;
            for(var key in conts){
                this.mapData.push({value:conts[key], key:key}); //Here we are creating the array to show on UI.
            }
        }
    }
}

LwcMapIterationController.apxc

public with sharing class LwcMapIterationController {
    @AuraEnabled(cacheable=true)
    public static Map < String, String > fetchMapData() {
        Map < String, String > mapOppAccount = new Map < String, String >();
        for(Opportunity opp : [SELECT ID, Account.Name, Name FROm Opportunity LIMIT 5])
        	mapOppAccount.put(opp.Name, opp.Account.Name);
        return mapOppAccount;
    }
}

So we have used JavaScript to iterate the map and store that in an object array list. After we iterate that array list using template in key and value in LWC. We have used wire method to call the apex method. For that first we import that method using standard import approach.

In Lightning we use aura:iteration to iterate list while in LWC we use template for:each={mapData} for:item="mapKey" to iterate the list.

In Lightning Web Components (LWC) the element which is direct child of iterate we need to give them a unique. So when we need to rerender that section LWC use this key to rerender only that section. If we don’t provide a key then LWC will give us an exception Elements within iterators must have a unique, computed key value.

Did you like this post or want to add anything, let me know in comments section. Happy programming 🙂

Advertisements

12 thoughts on “Iterate Map in Lightning Web Components

    1. Hi Magdalena,
      You just need nested for loops to iterate them.

      for(var key in conts){ //outer loop
      for(var nestedkey in conts[key]){ //inner loop
      this.mapData.push({value:nestedkey, key:(key == null ? ” : key), name : conts[key][nestedkey]});
      }
      }

  1. Hi,
    I have a map of Map<Account, List<Map>>.
    When I iterate I get a key but I get the whole Account , I need to just display the Account Name . I tried using key.Name but it shows undefined in console.
    Could you please help us how to display the name of account on UI.

  2. Greetings Tushar,

    I’m passing a Map. Would I use the same method to populate the object array list? If no, then how?

    Also, how would I access the fields of the records in the sObject List? I tried doing a nested template look using the values as keys, but nothing is printed out. I validated that indeed records are being added the the list.

    Thanks,
    Greg

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.