美好的一天,我一直在尝试按组标题显示数组,我从网络服务获取我的数组,我想按组标题显示项目
例子
组 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"
}
]
}
]
我无法粘贴所有数组数据,因为它太长了,但这是数组结构
这是我们如何做到的一种选择:
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]);
应用程序组件.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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句