Iterate Map List Values in Lightning Component

Apex Class:

public class SampleAuraController {
    
    @AuraEnabled
    Public static Map<string, List<string>> getMap(){ 
        Map<String, List<string>> mapObj = new Map<String, List<string>>();
        List<string> fruits = new List<String>{'Apple', 'Orange', 'Banana', 'Grapes'};
		List<string> vegetables = new List<String>{'Cabbage', 'Carrot', 'Potato', 'Tomato'};
		mapObj.put('Fruits', fruits);
        mapObj.put('Vegetables', vegetables);  
        return mapObj;
    }
}

Lightning Component:

<aura:component controller="SampleAuraController">
    <aura:attribute name="mapValues" type="object" />	
    <div class="slds-m-around_xx-large">
        <div class="slds-box slds-theme_default">
            <lightning:button label="Iterate Map" onclick="{!c.getMapValues}"/>
            <aura:iteration items="{!v.mapValues}"  var="mapKey" indexVar="key">  
                <strong><p>{!mapKey.key}</p></strong>
                <aura:iteration items="{!mapKey.value}" var="mapValue">
                    <p>{!mapValue}</p>
                </aura:iteration>
            </aura:iteration>
        </div>
    </div>
</aura:component>

Lightning Component JS Controller:

({
    getMapValues : function(component, event, helper) {
        var action = component.get("c.getMap");
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS"){
                var result = response.getReturnValue();
                var arrayMapKeys = [];
                for(var key in result){
                    arrayMapKeys.push({key: key, value: result[key]});
                }
                component.set("v.mapValues", arrayMapKeys);
            }
        });
        $A.enqueueAction(action);
    }
})

Output:

  • Sai Vineeth Maddula

    Hi, I have a requirement to display a generic html table based on parameters like object name and api names. I have referred your code to iterate map values on page. But, I wanted to display field labels in one row and the respective data below the field name. Can you help me how to develop logic for it.

  • santhi

    Hi Biswajeet,

    This example is really good. but i want to traverse through map<list,List>()
    but dont know how do i traverse these.

    Any help is appreciated.

    thanks,
    Santhi

  • Ramesh Singh

    hello ,

    i have to iterate map<Case,List> in lightning component
    when i print {!mapkey.key}

    its showing [Case (Id:5006F000023yjINQAY, CaseNumber:00001126, Priority:Medium, Status:New)]
    but i am not able to get the id attribute,
    please tell how can i get the case id