0

I have a dynamicly created record in LWC.js like this:

[ { “Id”: “00Q0D000006GAAJUA4", “Name”: “Jane Doe”, “FieldXYZ__c”: “Plane”, “FIELDABC__c”: “Seat”, “FIELDZUI__c”: “Instagram”, “FIELDUUUN__c”: “Easy Contract” } ]

Dynamicly means, which fields are queried is setup by MetaDataTypes. So it can be different fields and I cannot code them fix into the HTML Template. How would I display this in the LWC HTML Template with in an iteration, when I cannot fix code the fields?

normaly I would display them this way:

<template for:each={leads} for:item=“lead”>
  <div key={lead.Id} class=“card” data-id={lead.Id} onclick={handleClick}>
    <div class=“group” data-id={lead.Id}>{lead.Name}</div>
    <div class=“item” data-id={lead.Id}>FieldXYZ: {lead.FieldXYZ__c}</div>
    <div class=“item” data-id={lead.Id}>FIELDABC: {lead.FIELDABC__c}</div>
    <div class=“item” data-id={lead.Id}>FIELDZUI: {lead.FIELDZUI__c}</div>
    <div class=“item” data-id={lead.Id}>FIELDUUUN: {lead.FIELDUUUN__c}</div>
 </div>
</template>

Can I iterate over the delivered fields and how?

thanks

1 Answer 1

4

You can only iterate over Arrays, not Objects. There's no such thing as "dynamic" access in LWC.

This is usually pretty trivial. First, map out the data how you want it laid out.

this.leads = this.leads.map((lead) => ({
  Id: lead.Id,
  Name: lead.Name,
  values: Object.entries(lead)
    .filter((field) => field[0] !== "Id" && field[0] !== "Name")
    .map(([fieldName, value]) => ({
      fieldName,
      value,
    })),
}));

Which makes your template:

<div for:each={leads} 
     for:item="lead" 
     key={lead.Id} 
     class="card" 
     data-id={lead.Id} 
     onclick={handleClick}>
  <div class="group" 
       data-id={lead.Id}>
    {lead.Name}
  </div>
  <div class="item" 
       data-id={lead.Id} 
       for:each={lead.values} 
       for:item="fieldValue" 
       key={fieldValue.fieldName}>
    {fieldValue.fieldName}: {fieldValue.value}
  </div>
</div>
0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.