How to Iterate over Map in Lighting Web Component?

on

|

views

and

comments

Table of Contents

Introduction

Hello Awesome Developers, Here we will talk how we can iterate with JavaScript Map and display both Key & Value in HTML.

Recently, I had completed a requirement where I was getting some information from third party and then I need to display the Label & value dynamically.
In the requirement the data was coming in the forma of JSON where Key was label and value was value against that Label. 

Use Case

Suppose that you are getting the JSON data which have a single object or list of objects with label as key which needs to be displayed and value as value to be displayed in the HTML. 

Example JSON file is given below

				
					{
  "First Name": "Rack's",
  "Last Name": "Jackon",
  "Gender": "man",
  "Age": 24,
  "Street Address": "126",
  "City": "San Jone",
  "State": "CA",
  "PostalCode": "394221",
  "Phone Type": "home",
  "Phone Number": "7383627627"
}
				
			

Note:- Data can come from anywhere to your Lightning Web Component. For Example, a third party API, Apex class or from parent component.

Pain Point

As we know that dynamic binding is not supported in Lightning Web Component so we can not use the expression like below

data[‘First Name’] or something like that.

Solution Approach

As a solution what we can do is create a JavaScript Array and inside that JavaScript array we will push the data in the following format.

				
					{ 
    label: Key from JSON Object,
    Value: value from JSON object
}
				
			

Here is the sample code which will use above JSON object as example and push the data into a JavaScript Object.

				
					/* The Example JSON file */
let person = {
  "First Name": "Rack's",
  "Last Name": "Jackon",
  "Gender": "man",
  "Age": 24,
  "Street Address": "126",
  "City": "San Jone",
  "State": "CA",
  "PostalCode": "394221",
  "Phone Type": "home",
  "Phone Number": "7383627627"
}

/* Create an Array to store the final Outcome */
let finalOutcome = [];
for(let key in person){
    finalOutcome = [...finalOutcome, { key : key, value : person[key] } ];
}
console.log(finalOutcome);
				
			

In the above example, I have only taken a Single JSON object but in the real time there could be multiple JSON objects. Then you have to first Iterate over array and then Iterate over JSON object which will be item inside JavaScript Array. Example is given as below.

				
					{
  "data": [
    {
      "id": 7,
      "email": "michael.lawson@reqres.in",
      "first_name": "Michael",
      "last_name": "Lawson",
      "avatar": "https://reqres.in/img/faces/7-image.jpg"
    },
    {
      "id": 8,
      "email": "lindsay.ferguson@reqres.in",
      "first_name": "Lindsay",
      "last_name": "Ferguson",
      "avatar": "https://reqres.in/img/faces/8-image.jpg"
    },
    {
      "id": 9,
      "email": "tobias.funke@reqres.in",
      "first_name": "Tobias",
      "last_name": "Funke",
      "avatar": "https://reqres.in/img/faces/9-image.jpg"
    },
    {
      "id": 10,
      "email": "byron.fields@reqres.in",
      "first_name": "Byron",
      "last_name": "Fields",
      "avatar": "https://reqres.in/img/faces/10-image.jpg"
    },
    {
      "id": 11,
      "email": "george.edwards@reqres.in",
      "first_name": "George",
      "last_name": "Edwards",
      "avatar": "https://reqres.in/img/faces/11-image.jpg"
    },
    {
      "id": 12,
      "email": "rachel.howell@reqres.in",
      "first_name": "Rachel",
      "last_name": "Howell",
      "avatar": "https://reqres.in/img/faces/12-image.jpg"
    }
  ]
}
				
			

Let's Develop LWC

Ok. So now the time is to develop Lightning Web Component and see how we can display the information.

Go ahead and create a Lightning Web Component and you can name it anything like userInformation or userList

In the JavaScript store the Person information inside a variable and also create a variable to store the final outcome.

Prepare JavaScript class

				
					import { LightningElement } from 'lwc';

export default class UserInformation extends LightningElement {
    /* The Example JSON file */
    person = {
        "First Name": "Rack's",
        "Last Name": "Jackon",
        "Gender": "man",
        "Age": 24,
        "Street Address": "126",
        "City": "San Jone",
        "State": "CA",
        "PostalCode": "394221",
        "Phone Type": "home",
        "Phone Number": "7383627627"
    }

    finalOutcome = [];
}
				
			

Now, let’s add a function which will be invoked from a button and prepare the data. You can also call this function from connected callback or from another method.

				
					handleClick() {
        for(let key in this.person){
            this.finalOutcome = [...this.finalOutcome, { key : key, value : this.person[key] } ];
        }
        console.log(this.finalOutcome);
    }
				
			

Prepare HTML Template

As, we have prepared a variable finalOutcome. In the HTML file we will use a for loop and display the information

				
					<template>
    <lightning-card variant="Narrow"  title="JavaScript Map Example" icon-name="standard:user">
        <div class="slds-p-around_large">
            <lightning-button variant="brand" label="Display Information" title="Display Information" onclick={handleClick}></lightning-button>
        </div>
        <div class="slds-p-around_large">
            <template if:true={finalOutcome} for:each={finalOutcome} for:item="con" for:index="index">
                <li key={con.key}>
                    {con.key} &nbsp; {con.value}
                </li>
            </template>
        </div>
    </lightning-card>
</template>
				
			

Outcome

Once you have developed the HTML and JavaScript file you need to deploy the code to Salesforce or you can use Local Development to preview the outcome.

Once you will preview the component initially you will see the button only and when you click on the button the information will be displayed.

Complete Code

Please find the complete code below for the component

Next Steps

As a next step you can modify the above component and display the list of records dynamically from the given example file.

If you face any issues. Please do let me know

Amit Singh
Amit Singhhttps://www.pantherschools.com/
Amit Singh aka @sfdcpanther/pantherschools, a Salesforce Technical Architect, Consultant with over 8+ years of experience in Salesforce technology. 21x Certified. Blogger, Speaker, and Instructor. DevSecOps Champion
Share this

Leave a review

Excellent

SUBSCRIBE-US

Book a 1:1 Call

Must-read

How to start your AI Journey?

Table of Contents Introduction Are you tired of the same old world? Do you dream of painting landscapes with your code, composing symphonies with data, or...

The Secret Weapon: Prompt Engineering: 🪄

Table of Contents Introduction Crafting the perfect prompt is like whispering secret instructions to your AI muse. But there's no one-size-fits-all approach! Exploring different types of...

How to Singup for your own Production org?

Let's see how we can have our salesforce enterprise Salesforce Org for a 30-day Trial and use it as a Production environment. With the...

Recent articles

More like this

LEAVE A REPLY

Please enter your comment!
Please enter your name here

5/5

Stuck in coding limbo?

Our courses unlock your tech potential