This post explains how to iterate map of list values in Lightning web components(lwc)
showMapOfListValuesDemo.html
showMapOfListValuesDemo.js
showMapOfListValuesDemo.js-meta.xml
Result:
Demo:
Apex Class:
public inherited sharing class LWCExampleController {
@AuraEnabled(cacheable=true)
public static map<String, list<String>> returnMapOfListValues() {
map<String, list<String>> mapOfListValues = new map<String, list<String>>();
mapOfListValues.put('India', new list<String>{'Hyderabad', 'Delhi', 'Mumbaie'});
mapOfListValues.put('USA', new list<String>{'New York', 'Las Vegas', 'Miami'});
mapOfListValues.put('China', new list<String>{'Shenzhen', 'Guangzhou', 'Shanghai'});
return mapOfListValues;
}
}
<template>
<lightning-card title="Iterate Map Values Demo">
<template if:true={mapOfListValues}>
<table class="slds-table slds-table_bordered slds-table_cell-buffer slds-table_col-bordered">
<thead>
<tr class="slds-text-title_caps">
<th scope="col">
<div title="Key">Country Name (Key)</div>
</th>
<th scope="col">
<div title="Value">Popular City Names (List Values)</div>
</th>
</tr>
</thead>
<tbody>
<template for:each={mapOfListValues} for:item="keyValue">
<tr key={keyValue.key}>
<th scope="col">
<div>{keyValue.key}</div>
</th>
<template for:each={keyValue.value} for:item="value">
<div key={value}>
<b>{value}</b><br/>
</div>
</template>
</tr>
</template>
</tbody>
</table>
</template>
</lightning-card>
</template>
showMapOfListValuesDemo.js
import { LightningElement, track, wire } from 'lwc';
import getMapOfData from '@salesforce/apex/LWCExampleController.returnMapOfListValues';
export default class ShowMapOfListValuesDemo extends LightningElement {
@track mapOfListValues = [];
@wire(getMapOfData)
mapOfData({data, error}) {
if(data) {
for(let key in data) {
// Preventing unexcepted data
if (data.hasOwnProperty(key)) { // Filtering the data in the loop
this.mapOfListValues.push({key: key, value: data[key]});
}
}
}
else if(error) {
window.console.log(error);
}
}
}
showMapOfListValuesDemo.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="showMapOfListValuesDemo">
<apiVersion>45.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Result:
No comments:
Post a Comment