0

I am trying to get object value dynamically using nested for each loop in HTML. EX: In JS I have record somthing like this :

        this.tempData = [{ 'field1': 'name', 'field2': 'type' }];
        this.fields = ['field1', 'field2'];

In HTML Displaying values:

<template for:each={tempData} for:item="i" for:index="index">
<template for:each={fields} for:item="field" for:index="index1">
     <div  key={field}>
         {i.field} 
     </div>
     
     </template>
     </template>

but not able to get the record value ,however when I am using record statically like :

{i.field1}

{i.field2}

I am able to see the values . Please correct me where I am going worng?

4
  • i think you need to use {i[field]}.
    – Damecek
    Commented Aug 27, 2021 at 11:08
  • I had tried this but this expression is not allowed is LWC Commented Aug 27, 2021 at 11:20
  • since the nested loops were not working. I changed my approach , Created a child component and passed the vlaues to it to display and got success Commented Aug 27, 2021 at 12:08
  • are you passing a lot of values to the child component?
    – glls
    Commented Aug 27, 2021 at 17:18

1 Answer 1

0

Creating a child component and passing values down is definitely one of many approaches you can use, another approach can be to "restructure" or modify your json to include all the necessary metadata to iterate over the properties as follows:

from:

this.tempData = [{ 'field1': 'name', 'field2': 'type' }];
this.fields = ['field1', 'field2'];

to:

this.fieldData = [{fieldName: 'field1', fields: ['name']}, {fieldName: 'field2', fields: ['type']}]

template.html:

<template for:each={fieldData} for:item="item">
    <template for:each={item.fields} for:item="field">
       <div  key={field}>
         {field} 
       </div>
     </template>
 </template>

Just a heads up, when passing down arrays of data to children components, you need to consider the following:

Arrays Proxied When Passed to Child Components

A page that’s using a component that passes a large array of objects through layers of child components can become unresponsive.

1
  • yes @glls this approach also can be used but this will not work for my scenario Commented Sep 1, 2021 at 8:03

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .