gpt4 book ai didi

javascript - 将 JSON 数据数组分组到另一个数组

转载 作者:行者123 更新时间:2023-12-01 00:37:24 25 4
gpt4 key购买 nike

我正在构建一个 Angular 7 应用程序。在此应用程序中,我从服务器获取 JSON 数据,然后我想按特定键对其进行分组。我设法做到了这一点,但我不再拥有数组,而是某种对象。

启动 JSON 数据

[{
"id": 67,
"survey_id": 26,
"question_id": 63,
"user_id": 35,
"privacy": null,
"score": null,
"comment": "A nice little comment",
"binary": null,
"reasons": null,
"preferences": "{}",
"created_at_date": "2019-09-18",
"created_at_time": "19:53",
"user": {
"id": 35,
"fullname": "Michael Palin"
},
"can_manage": true
},
{
"id": 68,
"survey_id": 26,
"question_id": 64,
"user_id": 4,
"privacy": null,
"score": null,
"comment": "Another little comment",
"binary": null,
"reasons": null,
"preferences": "{}",
"created_at_date": "2019-09-18",
"created_at_time": "19:53",
"user": {
"id": 4,
"fullname": "Roland Smacker"
},
"can_manage": true
},
{
"id": 69,
"survey_id": 26,
"question_id": 65,
"user_id": 4,
"privacy": null,
"score": null,
"comment": "Some more comments",
"binary": null,
"reasons": null,
"preferences": "{}",
"created_at_date": "2019-09-18",
"created_at_time": "19:53",
"user": {
"id": 4,
"fullname": "Roland Smacker"
},
"can_manage": true
},
{
"id": 70,
"survey_id": 26,
"question_id": 66,
"user_id": 4,
"privacy": null,
"score": 5,
"comment": null,
"binary": null,
"reasons": null,
"preferences": "{}",
"created_at_date": "2019-09-18",
"created_at_time": "19:53",
"user": {
"id": 4,
"fullname": "Roland Smacker"
},
"can_manage": true
}

]

这是我的分组代码

setupStats() {
const groupBy = (array, key) => {
return array.reduce((result, currentValue) => {
(result[currentValue[key]] = result[currentValue[key]] || []).push(
currentValue
);
return result;
}, {});
};
const grouped = groupBy(this.collection, 'user_id');
console.log(grouped);
}

这是输出

{4: Array(3), 35: Array(1)}

4 和 35 是 user_ids。我希望它们获取数组的一部分,以便我可以循环它们,但我现在不能这样做。

最佳答案

如果您希望使用 *ngFor 指令将分组数据绑定(bind)到模板,您可以利用 keyvalue 管道来迭代分组对象:

<div *ngFor="let group of groupedItems | keyvalue">
<strong>{{ group.key }} {{ group.value.length }} items</strong>
<div *ngFor="let item of group.value">
{{item.id}} {{item.comment}}
</div>
</div>

您可以阅读有关 keyvalue pipe here 的信息.

关于javascript - 将 JSON 数据数组分组到另一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58000397/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com