Issue
I have this object. Now I want to iterate this using *ngFor to get the UI (image link is giving below). I am facing issue in making different section.
Here is my Object –
[
{
"number": 1,
"section": "Section 1"
},
{
"number": 2,
"section": "Section 1",
},
{
"number": 3,
"section": "Section 1"
},
{
"number": 1,
"section": "Section 2"
},
{
"number": 2,
"section": "Section 2"
},
{
"number": 1,
"section": "Section 3"
},
{
"number": 1,
"section": "Section 4"
},
{
"number": 2,
"section": "Section 4"
}
]
This is the screen which I want to develop
Please help. Thanks in advance!
Solution
You can use JavaScript’s array.reduce() to restructure your array in the format you want.
var data = [
{
"number": 1,
"section": "Section 1"
},
{
"number": 2,
"section": "Section 1",
},
{
"number": 3,
"section": "Section 1"
},
{
"number": 1,
"section": "Section 2"
},
{
"number": 2,
"section": "Section 2"
},
{
"number": 1,
"section": "Section 3"
},
{
"number": 1,
"section": "Section 4"
},
{
"number": 2,
"section": "Section 4"
}
]
let group = data.reduce((x, y) => {
x[y.section] = [...x[y.section] || [], y];
return x;
}, {});
console.log(group)