Lightning Web Components – How to Create Nested Template for:each for a Map of Arrays

javascriptlightning-web-components

How can I render out items in groups from a Javascript Map, where the key is the header string and the values are an array (for simplicity, let's just render the Label value from each element)?

From my early experiments, it seems LWC's for:each isn't flexible enough to do this without some backend data-wrangling, as it can't do computed expressions.

Data structure looks like this

Browser dev console showing Map keyed on string, with arrays as values

and I'm trying to get some kind of grouping from that that looks like this (don't worry about the aesthetics for now, this is more about the data structure traversal on the template)Mockup UI

Best Answer

You should be able to access elements of the array using a nested for:each and dot notation in your HTML file.

<template for:each={dataStructure} for:item="data">
    <th key={data.Key}>{data.Key}</th>
    <template for:each={data.value} for:item="dataValue">
        <td key={dataValue.Id}>{dataValue.Label}</td>
    </template>
</template>