In LWC we will always be working with JSON objects.
And one the tag that we use the most and that deals with JSON string is <template for:each /> tag in LWC.
This tag will only work with Array and not Objects. Don't do the mistake of trying to iterating through an object.
For that matter, the only reason we have to flatten our object when we get a nested object as a part of inner query in SOQL is because we can only use an Array with <template for:each /> tag.
In this example am gonna iterate through Array's with in an Array. If you are curious as to how the nested Array is going to look like, here is the JS file.
import { LightningElement, track } from 'lwc';
export default class App extends LightningElement {
data = [
{
id: '0001',
name: 'John',
location: 'India',
gender: 'male',
address: [{
street1: 'street 11',
street2: 'street 12',
city: 'city 1',
country: 'country 1',
pin: '999-001'
}]
},
{
id: '0002',
name: 'Janet',
location: 'US',
gender: 'female',
address: [{
street1: 'street 21',
street2: 'street 22',
city: 'city 2',
country: 'country 2',
pin: '999-000'
}]
},
{
id: '0003',
name: 'Doe',
location: 'UK',
gender: 'male',
address: [{
street1: 'street 31',
street2: 'street 32',
city: 'city 3',
country: 'country 3',
pin: '999-111'
}]
}
]
}
Now I will be iterating this Array in our template file. This is how the template file is going to look it.
<template>
<ul>
<template for:each={data} for:item="person">
<div key={person.id} class="slds-grid slds-wrap">
<div class="slds-4-of-12 slds-p-horizontal_large"><strong>Name: </strong>{person.name} </div>
<div class="slds-4-of-12 slds-p-horizontal_large" ><strong>Gender:</strong> {person.gender} </div>
<div class="slds-4-of-12 slds-p-horizontal_large"><strong>Location:</strong> {person.location}</div>
<template for:each={person.address} for:item="person_address">
<div class="slds-grid slds-wrap" key={person_address.pin}>
<div class="slds-2-of-12 slds-p-right_medium"><strong>Street 1: </strong>{person_address.street1}</div>
<div class="slds-2-of-12 slds-p-right_medium"><strong>Street 2: </strong>{person_address.street2}</div>
<div class="slds-2-of-12 slds-p-right_medium"><strong>City : </strong>{person_address.city}</div>
<div class="slds-2-of-12 slds-p-right_medium"><strong>Country: </strong>{person_address.country}</div>
<div class="slds-2-of-12 slds-p-right_medium"><strong>Pin: </strong>{person_address.pin}</div>
<div class="slds-2-of-12 slds-p-right_medium"></div>
</div>
</template>
</div>
</template>
</ul>
</template>
Here's the playground link in case you are interested.
Learn it by building it
Every course, every code repository, the discussion group and certificates of completion — one subscription.