Wednesday, 9 April 2025

Display Map with List Value in a Lightning Component #Salesforce

πŸ—Ί️ Displaying a Map with List Values in a Lightning Component

When working with complex data structures in Salesforce, using a Map with a List as its value is common in Apex. But displaying this structure in a Lightning Component (Aura or LWC) requires a few tricks. This blog walks through how to pass and render a Map<String, List<Object>> in a user-friendly way.


πŸ“¦ Use Case

You're retrieving a list of Contacts grouped by Account Name, like:


Map<String, List<Contact>> contactsByAccount = new Map<String, List<Contact>>();

Now, you want to display each account with its related contacts in a Lightning component.


⚙️ Apex Controller


@AuraEnabled(cacheable=true) public static Map<String, List<Contact>> getContactsByAccount() { Map<String, List<Contact>> result = new Map<String, List<Contact>>(); for (Account acc : [SELECT Id, Name, (SELECT Id, Name, Email FROM Contacts) FROM Account LIMIT 10]) { result.put(acc.Name, acc.Contacts); } return result; }

🧩 Aura Component Example


<aura:component controller="YourApexClass"> <aura:attribute name="contactsMap" type="Object"/> <aura:handler name="init" value="{!this}" action="{!c.doInit}"/> <aura:iteration items="{!v.contactsMap}" var="key"> <p><strong>{!key}</strong></p> <aura:iteration items="{!v.contactsMap[key]}" var="con"> <p>- {!con.Name} ({!con.Email})</p> </aura:iteration> </aura:iteration> </aura:component>


⚡ Client-side Controller (JS)


doInit: function(component, event, helper) { var action = component.get("c.getContactsByAccount"); action.setCallback(this, function(response) { if (response.getState() === "SUCCESS") { component.set("v.contactsMap", response.getReturnValue()); } }); $A.enqueueAction(action); }


✅ Best Practices

  • Use @AuraEnabled(cacheable=true) for better performance.

  • Always check for null values in JS to avoid runtime errors.

  • For LWC, transform the map into an array format using Apex before returning.


πŸ’¬ Final Thoughts

Using a Map<String, List<Object>> structure allows powerful grouping in Apex. With the right approach, rendering it in the Lightning UI is clean and intuitive.


No comments:

Post a Comment