groupby ngFor angular2

groupby ngFor angular2

美好的一天,我一直在尝试按组标题显示数组,我从网络服务获取数组,我想按组标题显示项目

示例

第 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]);

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