Saturday, May 4, 2019

How to iterate map values in Lightning Web Components(lwc)

This post explains how to iterate map values in Lightning web components(lwc)


Apex Class
public inherited sharing class LWCExampleController {
    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;
    <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">
                    <tr class="slds-text-title_caps">
                        <th scope="col">
                            <div title="Key">State Name (Key)</div>
                        <th scope="col">
                            <div title="Value">Capital City Name (Value)</div>
                    <template for:each={mapOfValues} for:item="keyValue">
                        <tr key={keyValue.key}>
                            <th scope="col">
                            <th scope="col">


import { LightningElement, track, wire } from 'lwc';
import getMapOfData from '@salesforce/apex/LWCExampleController.returnMapOfValues';

export default class ShowMapLWCDemo extends LightningElement {
    @track mapOfValues = [];

    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) {

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="" fqn="showMapLWCDemo">


No comments:

Post a Comment