Onclick of button iterate and display map from server to client side controller



Aura 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;
    }
}

c:SampleAuraController

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

JS

({
    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();
                console.log('res'+JSON.stringify(result));
                var arrayMapKeys = [];
                for(var key in result){
                    arrayMapKeys.push({key: key, value: result[key]});
                }
                component.set("v.mapValues", arrayMapKeys);
            }
        });
        $A.enqueueAction(action);
    }
})


SampleAuraController_app

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

O/p

Onclik of iterate Map

displays

Fruits
Apple
Orange
Banana
Grapes

Vegetables
Cabbage
Carrot
Potato

Tomato


Comments

Popular posts from this blog

Delete Multiple Records -Custom Datatable

Dynamic Custom Datatable using dual List

Dynamic Standard Datatable Using Fieldset