This post explains how to iterate map values in Lightning web components(lwc)
showMapLWCDemo.js-meta.xml
Result
Demo:
Apex Class
showMapLWCDemo.jspublic inherited sharing class LWCExampleController {
@AuraEnabled(cacheable=true)
public static map<String, String> returnMapOfValues() {
map<String, String> mapOfValues = new map<String, String>();
mapOfValues.put('Telanagana', 'Hyderabad');
mapOfValues.put('Arunachal Pradesh', 'Itanagar');
mapOfValues.put('Assam', 'Dispur');
mapOfValues.put('Bihar', 'Patna');
mapOfValues.put('Gujarat', 'Gandhinagar');
return mapOfValues;
}
}
showMapLWCDemo.html<template>
<lightning-card title="Iterate Map Values Demo">
<template if:true={mapOfValues}>
<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">State Name (Key)</div>
</th>
<th scope="col">
<div title="Value">Capital City Name (Value)</div>
</th>
</tr>
</thead>
<tbody>
<template for:each={mapOfValues} for:item="keyValue">
<tr key={keyValue.key}>
<th scope="col">
<div>{keyValue.key}</div>
</th>
<th scope="col">
<div>{keyValue.value}</div>
</th>
</tr>
</template>
</tbody>
</table>
</template>
</lightning-card>
</template>
import { LightningElement, track, wire } from 'lwc';
import getMapOfData from '@salesforce/apex/LWCExampleController.returnMapOfValues';
export default class ShowMapLWCDemo extends LightningElement {
@track mapOfValues = [];
@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.mapOfValues.push({value:data[key], key:key});
}
}
}
else if(error) {
window.console.log(error);
}
}
}
showMapLWCDemo.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="showMapLWCDemo">
<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