How to use Map in Lightning Component?

Map: This is an collection of Key-Value pair items. A Map can’t contain duplicate keys.

How to use Map in Lightning Component?

A. How can we define and access the Map in Lightning Component?
B. How can we define and access the Map in Lightning Component through Server?

A. How can we define and access the Map in Lightning Component?

Step 1: Create a Lightning Component Bundle named “simpleMap”.

simpleMap.cmp | showing the values from a map

<aura:component implements="flexipage:availableForAllPageTypes">

	<aura:attribute name="capitalMap" type="Map" default="{key1:'value1', key2:'value2'}"/>
	
	<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
			
	<span style="font-size: 1rem;">Capital</span>

	The capital of India: {!v.capitalMap.India}
	The capital of Nepal: {!v.capitalMap.Nepal}
	
					
</aura:component>

simpleMapController.js | define the map at controller.js file

({
	doInit : function(component, event, helper) {
		var capitalMap = component.get("v.capitalMap");

		//capitalMap["KEY"] = "VALUE";
		capitalMap["India"] = "New Delhi";
		capitalMap["Nepal"] = "KathMandu";
		
		component.set("v.capitalMap",capitalMap);
        console.log("The Capital of India: "+component.get("v.capitalMap")["India"]);		
	}
})

B. How can we define and access the Map in Lightning Component through Server?

Step 1: Need to write Apex Class where we will define the Map at Class level.

SimpleMapController.apxc | returns the map from server side

public with sharing class SimpleMapController {
	
	@AuraEnabled
	public static Map<String, String> getCapitals(){

		Map<String, String> capitalsMap = new Map<String, String>();
		capitalsMap.put('India', 'New Delhi');
		capitalsMap.put('Nepal', 'KathMandu');

		return capitalsMap;
		
	}
}

Step 2: Create a Lightning Component Bundle named “simpleMap”.

simpleMap.cmp | showing the values from a map

<aura:component implements="flexipage:availableForAllPageTypes" controller="SimpleMapController">

	<aura:attribute name="capitalsMap" type="Map"/>
	
	<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>

	<span style="font-size: 1rem;">Capital</span>

	The capital of India: {!v.capitalsMap.India}
	The capital of Nepal: {!v.capitalsMap.Nepal}
					
</aura:component>

simpleMapController.js | to call the helper function

({
	doInit : function(component, event, helper) {
		helper.performShowingCapitals(component, event);
 	}
})

simpleMapHelper.js | to set the map attribute of the component to the map returned from server side

({
	performShowingCapitals : function(component, event) {
		var action = component.get("c.getCapitals");
		this.setupPerformShowingCapitalsAction(component, action);
		$A.enqueueAction(action);
	},

	setupPerformShowingCapitalsAction : function(component, action) {

		action.setCallback(this, function(response){
        	this.handlePerformShowingCapitalsResultsCallBack(component, response);
        });	
	},

	handlePerformShowingCapitalsResultsCallBack : function(component, response) {

		var responseState = response.getState();
		var responseError = response.getError();
		var responseValue = response.getReturnValue();

		switch(responseState){

			default: break;
			case 'NEW': break;
			case 'RUNNING': break;

			case 'SUCCESS':

				if(responseValue != null)			
					component.set("v.capitalsMap", responseValue);
				break;
					

			case 'INCOMPLETE': break;
			case 'ERROR': 
				console.log('Response Error-->'+JSON.stringify(responseError));
				break;

		}
	}
})

Steps to remember

1. Declare the attribute of Map type in Component Level.
2. Need to set the Map sent by Apex Class or standalone in your javascript file to Map attribute in your Lightning Component by javascript file.
3. Need to print out the value of the Map in Component file in this way: {!v.mapAttribute.key}
4. Need to print out the value of the Map in javascript file in this way: component.get(“v.mapAttribute”)[“key”]

5,418 total views, 1 views today

Rating: 5.0/5. From 5 votes.
Please wait...

You may also like...