Lightning Web Components – How to Display Object in LWC

apexjavascriptlightning-web-components

I have a requirement, to display specific data on custom component.

  • Data is grouped by parameter into an object (up to 13)
  • Object contains array of objects
  • Object into array have 3 another parameters
unique_key_name1: [{
    outcome: 'string',
    quote: 'string',
    source: 'string'
  },{
    outcome: 'string',
    quote: 'string',
    source: 'string'
  }],
unique_key_name2: [{
    outcome: 'string',
    quote: 'string',
    source: 'string'
  },{
    outcome: 'string',
    quote: 'string',
    source: 'string'
  }]

I need to create accordion section into component with unique_key_name into accordion label and all values from array object inside.

I have no idea, how to iterate through object (and don't even know, is it possible). Any ideas for solution or tips with displaying whole objects ?
Maybe I need to rebuild data received from controller, and this format I described is wrong ?
I appreciate any help !

Best Answer

You can't iterate over objects, you iterate over arrays. That means you need to convert your object-style data into array-style data. For example:

let output = Object.entries(data).map(
  ([label, values], id ) => ({ label, values, id })
);

Which transforms your data into:

[
  {
    "label": "unique_key_name1",
    "values": [
      { "outcome": "string", "quote": "string", "source": "string" },
      { "outcome": "string", "quote": "string", "source": "string" }
    ],
    "id": 0
  },
  {
    "label": "unique_key_name2",
    "values": [
      { "outcome": "string", "quote": "string", "source": "string" },
      { "outcome": "string", "quote": "string", "source": "string" }
    ],
    "id": 1
  }
]

From here, you can iterate over your output:

<template for:each={accordionSection} for:item="section">
  <lightning-accordion key={section.label} label={section.label}>
    <template for:each={section.values} for:item="value">
      <div key={value.id}>
        Outcome: {value.outcome}
        Quote: {value.quote}
        Source: {value.source}
      </div>
    </template>
  </lightning-accordion>
</template>

If the fields were also dynamic, you'd have to also convert them into an array suitable for displaying the values. Something like the following would probably be sufficient:

let output = Object.entries(data).map(([label, values], id) => ({
  id,
  label,
  values: Object.entries(values).map(([fieldName, fieldValue]) => ({
    fieldName,
    fieldValue,
  })),
}));
Related Topic