Concepts or coding lessons of Salesforce that you can implement easily

Easily Iterate Map in Lightning Web Component

In LWC project, we usually stuck how to iterate Map in Lightning Web Component
Here is the example you can use to iterate Map.

1. Create Apex class StudentController.cls:

public class StudentController {
@AuraEnabled(cacheble=true)
public static Map<String, String> fetchStudentData(){
Map<String, String> mapStudentData = new Map<String, String>();
mapStudentData.put('Om','BCS');
mapStudentData.put('Sai','BTech');
mapStudentData.put('Ram','BE Computer Science');
mapStudentData.put('Radhe','BE Civil');
return mapStudentData;
}
}


2. Create LWC LWCStudentMap.html:

<template>
    <lightning-card icon-name="standard:account" variant="base" title="LWC Map Demo">
      <table class="slds-table slds-table_cell-buffer slds-table_bordered">
        <thead>
            <tr class="slds-line-height_reset">
                <th scope="col"> Name </th>
                <th scope="col"> Faculty </th>
            </tr>
        </thead>
        <tbody>
            <template for:each={mapStudentData} for:item="objMap">
                <tr class="slds-hint-parent" key={objMap.key}>
                    <th scope="col">
                        <div title={objMap.key}> {objMap.key} </div>
                    </th>
                    <th scope="col">
                        <div title={objMap.value}> {objMap.value} </div>
                    </th>
                </tr>
            </template>
        </tbody>
      </table>>
    </lightning-card>
</template>


3. Create LWC LWCStudentMap.js:

import { LightningElement, track, wire } from 'lwc';
import fetchStudentData from '@salesforce/apex/StudentController.fetchStudentData'

export default class LWCStudentMap extends LightningElement {
    @track mapStudentData = [];
    @track error;

    @wire(fetchStudentData)
    wiredData({ error, data }) {
      if (data) {
        console.log('Data', data);
        var consts = data;
        for(var key in consts)
            this.mapStudentData.push({value:consts[key], key:key});
      } else if (error) {
        console.error('Error:', error);
        this.error = error;
      }
    }
}


Output: 


Subscribe blog for More updates !!! 


Read More: WhatsApp on Salesforce Integration in 5 Steps
                    Which Salesforce API Do I Use in Integration?
                    When To Use Salesforce REST API  
                   When To Use Salesforce SOAP API 
                   When To Use Salesforce Bulk API 


Latest Salesforce Interview Questions and Answers:

loading...

No comments:

Post a Comment