Я создаю приложение 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.Я хотел бы, чтобы они получили части массива, чтобы я мог зациклить их, что я не могу сделать сейчас.