Hello Friends ,
Here we are going to discuss how to use map in Lightning Web Component (LWC) .
Sample code
Here we are going to discuss how to use map in Lightning Web Component (LWC) .
Sample code
lwcMyMapIteration.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>
lwcMyMapIteration.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.
}
}
}
}
LwcMyMapIterationController.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 15])
mapOppAccount.put(opp.Name, opp.Account.Name);
return mapOppAccount;
}
}