Convert a List from a Map in Lightning Component

Convert a List from a Map in Lightning Component

In many projects, we have seen that we need to iterate a Map in Lightning component to satisfy the business requirement. But, it’s not possible in straightforward to iterate the Map at Component level. We have a solution for this. We can create a List from Map. We can create a List with Key and Value identifiers from a Map and then iterate the List and compare the Key and Value, if applicable.

Step 1: Need to create a Selector Class to return all the Contact records in a Map.

ContactSelector.apxc |  to return the Map of Contact records

public with sharing class ContactSelector {
	public static Map<Id,Contact> selectRecordsMap(){		
		return new Map<Id, Contact>([SELECT Id, Name, AccountId FROM Contact]);
	}
}

Step 2: To call the Selector Class(ContactSelector) to get the Map of Contact records.

SimpleMaptoListController.apxc |  to call the Selector Class “ContactSelector

public with sharing class SimpleMaptoListController {
	
	@AuraEnabled
	public static Map<Id,Contact> getContacts(){
		return ContactSelector.selectRecordsMap();
	}
}

Step 3: Create a Component Bundle named “simpleMaptoList”.

simpleMaptoList.cmp | to iterate the List converted from a Map returned from Server Side

<aura:component implements="flexipage:availableForAllPageTypes" controller="SimpleMaptoListController">
	<aura:attribute name="selectedContact" type="String"/>
	<aura:attribute name="contactList" type="List"/>
	
	<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>

	<lightning:card title="">
		<aura:set attribute="title">
			<lightning:icon iconName="utility:connected_apps" size="small"/>
			<span style="font-size: 2rem;" >Map to List</span>
		</aura:set>
		<lightning:layout multiplerows="true" verticalalign="center">
			<lightning:layoutItem padding="around-small" size="6">				
				<lightning:select name="Select a Contact" label="Select a Contact" aura:id="contactSelect" value="{!v.selectedContact}">
			        <aura:iteration items="{!v.contactList}" var="con">
                                    <option text="{!con.value}" value="{!con.key}"/>
			         </aura:iteration>
				</lightning:select> 
			</lightning:layoutItem>
		</lightning:layout>
	</lightning:card>
</aura:component>

simpleMaptoListController.js |  to call the helper function

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

simpleMaptoListHelper.js | to convert a List from a Map returned from Server Side and to set the List variable in the Component

({
	performShowingContacts : function(component, event) {
		var action = component.get("c.getContacts");
		//action.setStorable();
		this.setupPerformShowingContactsAction(component, action);
		$A.enqueueAction(action);
	},

	setupPerformShowingContactsAction : function(component, action) {

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

	handlePerformShowingContactsResultsCallBack : function(component, response) {

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

		var contacts = [];
		
		switch(responseState){

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

			case 'SUCCESS':

				if(responseValue != null){
					for(var key in responseValue){
						contacts.push({
							key: key,
							value: responseValue[key].Name
						});
					}
				}
				component.set("v.contactList", contacts);
				break;
					

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

		}
	}
})

Steps to Remember

1. Create Apex Class to return the Map to Lightning Component.
2. Declare the List attribute in .cmp file.
3. In helper.js file, declare an array (in this assignment, we have declared an array named “contacts[]”) in which we will store the Map with Key-Value Pair.
4. Then, need to push the Key – Value pair into this array by looping the responseValue(Map) from Server Side just like

for(var key in responseValue){
 contacts.push({
 key: key,
 value: responseValue[key].Name
 });
}

5. Need to set the List attribute of component with this array which we have created in helper.js file.
6. At last, you have to iterate the List attribute to show the result in your component just like

<aura:iteration items="{!v.contactList}" var="con">
  <option text="{!con.value}" value="{!con.key}"/>
</aura:iteration>

7,661 total views, 2 views today

Rating: 5.0/5. From 3 votes.
Please wait...
This entry was posted in Lightning Components. Bookmark the permalink.

Leave a Reply