How to render Map in LWC
Render Map in LWC
LWC for:each can't use Map to show elements, but it's easy to make it happen!
How to render Map<String, SObject> in LWC?
LWC for:each can't use Map to show elements, but it's easy to make it happen!
Get the data from the backend:
apex
@AuraEnabled(cacheable=true)
public static Map<String, Account> getAccounts() {
Map<String, Account> accounts = new Map<String, Account>();
for (Account account : [
SELECT Id, Name, NumberOfEmployees, (SELECT Id, Name, Email, Phone FROM Contacts)
FROM Account
]) {
accounts.put(account.Name, account);
}
return accounts;
}Then we simply transform the map into an array:
javascript
@wire(getAccounts, {})
wiredAccounts({ data, error }) {
if(data) {
this.data = Object.entries(data).map(([key, value]) => ({
name: key,
employees: value.NumberOfEmployees,
contacts: value.Contacts
}));
} else if(error){
console.error(error)
}
}Why can it be useful?
Simplified HTML looks like this:
markup
<template>
<template for:each={data} for:item="account">
<template for:each={account.contacts} for:item="contact">
<h3 key={account.Name}>{contact.Name}</h3>
</template>
</template>
</template>The final solution can look like this:

This can be useful for any kind of nested data, such as List of Lists, Maps, or Wrappers. The principle is to parse data into an Array, which then can be rendered by LWC for:each.


