美好的一天,我一直试图按群组标题显示数组,我从网络服务获取数组,我想按群组标题显示项目
示例
组别1 第1项 第2项 第3项
组2 第1项 第2项 第3项
这是我的数组
[
{
"id": "1",
"title": "Item 1",
"groups": [
{
"id": "2",
"title": "Communication"
}
]
},
{
"id": "2",
"title": "Item 2",
"groups": [
{
"id": "2",
"title": "Communication"
}
]
},
{
"id": "3",
"title": "Item 1",
"groups": [
{
"id": "1",
"title": "Creativie Art"
}
]
},
{
"id": "4",
"title": "Item 3",
"groups": [
{
"id": "2",
"title": "Communication"
}
]
},
{
"id": "5",
"title": "Item 2",
"groups": [
{
"id": "1",
"title": "Creativie Art"
}
]
},
{
"id": "6",
"title": "Item 3",
"groups": [
{
"id": "1",
"title": "Creativie Art"
}
]
}
]
我无法粘贴所有数组数据,因为它太长但这是数组结构
答案 0 :(得分:5)
以下是我们如何做到这一点的一个选项:
<强> app.component.ts 强>
const groupsDict = this.arr.reduce((acc, cur) => {
cur.groups.forEach(({ id, title}) => {
acc[id] = acc[id] || { id, title };
acc[id].items = acc[id].items || [];
acc[id].items.push({ id: cur.id, title: cur.title });
});
return acc;
}, {});
this.groups = Object.keys(groupsDict).map(x => groupsDict[x]);
<强> app.component.html 强>
<div class="grid">
<div *ngFor="let group of groups" class="col">
<h2>{{ group.title }}</h2>
<div *ngFor="let item of group.items">
{{ item.title }}
</div>
</div>
</div>
<强> Stackblitz Example 强>