Iterate over Map in Salesforce Lightning

Here is a code sample for iterating over Map in Salesforce Lightning, returned from Apex class to the Lightning Controller.

Apex class: LightningMapExampleController.cls

public with sharing class LightningMapExampleController {
    public static Map<String,List<Opportunity>> getOpportunityTypeMap() {
        Map<String,List<Opportunity>> opportunityTypeToOpportunityMap = new Map<String,List<Opportunity>>();
        for(Opportunity opp: [SELECT Id,Name,Type FROM Opportunity WHERE Type != null LIMIT 50]){            
                opportunityTypeToOpportunityMap.put(opp.Type, new List<Opportunity>());
        return opportunityTypeToOpportunityMap;

Lightning Component: LightningMapIterateExample.cmp

Lightning Component Controller: LightningMapIterateExampleController.js

<aura:component controller="LightningMapExampleController" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome" access="global">
    <aura:attribute name="opportunityMap" type="List"/> <!-- Map will be defined as List type--> 
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />

    <div class="slds-card">
        <aura:iteration items="{!v.opportunityMap}" var="MapVar" >
                <aura:iteration items="{!MapVar.value}" var="opportunity" >
                    <li>- {!opportunity.Name}</li>
    doInit : function(component, event, helper) {
 var action = component.get("c.getOpportunityTypeMap");        
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") { 
                //Returned Map from Apex
                var opportunityMap = response.getReturnValue();

                //List of object to hold data from Map 
                var opportunityObjectMap = new Array();

                for(var i in opportunityMap){
                        key : i,
                        value : opportunityMap[i]

                component.set("v.opportunityMap", opportunityObjectMap);
Iterate over Map in Salesforce Lightning

Hope that this blog would help, let me know in comments if you have any suggestions.


Was this post useful? If yes then please share.

Comments (2)

  1. Poonam says:

    hi, I tried implementing your solution and I am gettin my values like this
    D – basically the string is not being displayed properly,
    I did the exact same implementation as yours still not able to get the proper result.

Leave a Comment

All fields marked with an asterisk (*) are required