How to iterate map in Salesfore Lightning?

Apex Class:

public class LightningController {
    @AuraEnabled
    public static Map < String, String > fetchMapData() {
        Map < String, String > mapCustomer = new Map < String, String >();
        mapCustomer.put('Sample', 'Value');
        mapCustomer.put('Sample1', 'Value1');
        mapCustomer.put('Sample2', 'Value2');
        mapCustomer.put('Sample3', 'Value3');
        system.debug(mapCustomer);         
        return mapCustomer;
    }
}

Component:

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes" access="global" controller="LightningController">
    <ui:button label="Fetch" press="{!c.fetch}"/>
    <br/><br/>
    <aura:attribute name="showBool" type="Boolean" default="false"/>
    <aura:attribute name="customers" type="List" />
    <aura:renderIf isTrue="{!v.showBool}">
        <aura:iteration items="{!v.customers}" var="cus" indexVar="key">
            {!cus.key} - {!cus.value}<br/><br/>
        </aura:iteration>
    </aura:renderIf>
</aura:component>

Controller:

({
fetch : function(component, event, helper) {
        var custNo = component.get("v.custNo");
var action = component.get("c.fetchMapData");   
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {                
                var custs = [];
                var conts = response.getReturnValue();
                for ( key in conts ) {
                    custs.push({value:conts[key], key:key});
                }
                component.set("v.customers", custs);
                component.set("v.showBool", true);
            } 
});           
        $A.enqueueAction(action); 
}
})

App:

<aura:application >
    <c:MapComponent/>

</aura:application>

Output:


Cheers!!!

No comments:

Post a Comment