I have the following JSON data but would like to implement the HTML page such that it shows the parent as the header and all the children under the same parent under the content and then follow on by the second parent as the header and all the children under the second parent under the content. How would I be able to do so? An example would be like the following.
Sample 1
Product 1 - Test Product 1
Product 2 - Test Product 2
Sample 2
Product 1 - Test Product 1
"sampleList": [
{
"parent": "Sample 1",
"children": [
{
"product": "Product 1",
"name": "Test Product 1"
}
]
},
{
"parent": "Sample 1",
"children": [
{
"product": "Product 2",
"name": "Test Product 2"
}
]
},
{
"parent": "Sample 2",
"children": [
{
"product": "Product 1",
"name": "Test Product 1"
}
]
}
]
CodePudding user response:
- With
Array.reduce()
to perform group byparent
and concatenate array. - Create a new array from result 1 with each object element has
parent
andchildren
property.
let grouped = this.sampleList.reduce((groups, current) => {
groups[current.parent] = groups[current.parent] || [];
groups[current.parent].push(...current.children);
return groups;
}, Object.create(null));
this.groupedSampleList = Object.keys(grouped).map((key) => ({
parent: key,
children: grouped[key],
}));
If you use es2017
, you can work with Object.entries()
as:
this.groupedSampleList = Object.entries(grouped).map((value) => ({
parent: value[0],
children: value[1],
}));
<div *ngFor="let parent of groupedSampleList">
<strong>{{ parent.parent }}</strong>
<div *ngFor="let child of parent.children">
{{ child.product }} - {{ child.name }}
</div>
</div>
CodePudding user response:
The JSON data structure provided contains duplicate keys which is not ideal. Also, parents with the same value have children stored in separate locations. If the format could be improved such that each parent and child are separate items in the list, it can be easily performed iteratively using a ngFor, which allows you to iterate through data. Providing the JSON key will display the needed child elements. I have included an example below. https://angular.io/api/common/NgForOf
Reformatted Data:
sampleList":
[
{
"parent": "Sample 1",
"children": [
{
"product": "Product 1",
"name": "Test Product 1",
},
{
"product": "Product 1",
"name": "Test Product 1",
}],
},
{
"parent": "Sample 2",
"children": [
{
"product": "Product 1",
"name": "Test Product 1",
}]
}
]
<li *ngFor="let item of sampleList; index as I;">
<h3> {{item.parent}} </h3>
<li *ngFor="let item2 of sampleList[I].children;">
<div> {{item2.product}} - {{item2.name}}</div>
</li>
</li>