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
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.
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
Note:- Data can come from anywhere to your Lightning Web Component. For Example, a third party API, Apex class or from parent component.
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.
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.
Here is the sample code which will use above JSON object as example and push the data into a JavaScript Object.
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.
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.
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.
As, we have prepared a variable finalOutcome. In the HTML file we will use a for loop and display the information
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.
Please find the complete code below for the component
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