Wednesday, January 8, 2020

How to Iterate over map with list as values in lightning web components

How to Iterate over map with list as values in lightning web components
This blog post will explain "How to Iterate over map with list as values in lightning web components".


mapdemolwc.html



<template>
    <lightning-card>
        <table class="slds-table slds-table_cell-buffer slds-table_bordered">
            <thead>
              <tr class="slds-line-height_reset">
                <th class="" scope="col">
                  <div class="slds-truncate" title="Key">Key</div>
                </th>
                <th class="" scope="col">
                  <div class="slds-truncate" title="Value">Value</div>
                </th>
            </tr>
        </thead>
        <tbody>
            <template for:each={mapkeyvaluestore} for:item="mapkey" for:index="index">
                <tr key={mapkey.key}>
                    <th scope="col">
                     {mapkey.key}
                    </th>
                    <th scope="col">
                    <template for:each={mapkey.value} for:item="mapval" for:index="index1">
                      <div key={mapval}>
                     
                        {mapval}
                     
                    </div>
                
                    </template>
                  </th>
                </tr>
            </template>
        </tbody>
        </table>
    </lightning-card>
</template>


mapdemolwc.js



/* eslint-disable no-console */
 /* eslint-disable guard-for-in */
/* eslint-disable vars-on-top */

import { LightningElement, track, wire } from 'lwc';
import getDataFromApex from '@salesforce/apex/mapkeyvalueapexcontroller.methodName';
export default class Mapdemolwc extends LightningElement {
@track mapkeyvaluestore=[];

@wire(getDataFromApex)
getResults(result){
if(result.data){
    for(var key in result.data){
     this.mapkeyvaluestore.push({key:key,value:result.data[key]});
    }
   

  }
  else{
    console.log('Some error occured');
  }

 }

}


mapkeyvalueapexcontroller.cls



public with sharing class mapkeyvalueapexcontroller {
    @AuraEnabled(cacheable=true)
    public static map<string,List<string>> methodName(){
        map<string,List<string>> mapkeyvaluestore=new map<string,List<string>>();
        mapkeyvaluestore.put('key1',new List<string>{'STORE1','STORE6'} );
        mapkeyvaluestore.put('key2',new List<string>{'STORE2','STORE7'});
        mapkeyvaluestore.put('key3',new List<string>{'STORE3','STORE8'});
        mapkeyvaluestore.put('key4',new List<string>{'STORE4','STORE9'});
        mapkeyvaluestore.put('key5',new List<string>{'STORE5','STORE10'});
        return mapkeyvaluestore;
    }
    public mapkeyvalueapexcontroller() {

    }
}

lightningapp.app



<aura:application extends="force:slds">
<c:mapdemolwc></c:mapdemolwc>
</aura:application>      

No comments:

Post a Comment