Issue
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"
}
]
}
]
Solution
- With
Array.reduce()to perform group byparentand concatenate array. - Create a new array from result 1 with each object element has
parentandchildrenproperty.
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>
Answered By - Yong Shun
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.