LWC: Can a “<template for:each=" be used with an inner "<template for:each=" where the inner for-each gets its value using the key from the outer

iterationlightning-web-componentslooptemplate

I was looking to do the following and I'm not sure if it's possible in LWC.

I have a list of records which I'd like to loop through in the UI. I also have a map of records where the key is the iD of the records in the first list. I'd iike to loop through a list of records in my inner loop where the inner list has come from using the map with the key as the ID of the outer record being looped.

The desired code being something like

    <template for:each={transactions} for:item="transaction">
      <div class="rows" key={transaction.Id}>
          {transaction.Name}
      </div>
      <template for:each={transactionIdToDetailsMap[{transaction.Id}]} for:item="detail">
        <div class="rows" key={detail.Id}>
           {detail.Name}
        </div>
      </template>
   </template>

It seems this is not possible using template's. Does anyone have any tips on the best way I can achieve this? Thanks in advance for any tips on best approaches.

Best Answer

This is not possible in Aura or LWC, actually. for:each must have an Array to work off of. That means you must structure your data such that:

<template for:each={transactions} for:item="transaction">
  <div class="rows" key={transaction.Id}>
      {transaction.Name}
  </div>
  <template for:each={transaction.details} for:item="detail">
    <div class="rows" key={detail.Id}>
       {detail.Name}
    </div>
  </template>

This is a trivial transformation in JavaScript, though:

this.transactions = this.transactions.map(
  (transaction) => ({
    ...transaction,
    details: this.transactionIdToDetailsMap[transaction.Id]
  })
);