I am building an Angular 7 app. In this app I am fetching JSON data from the server that I then want to group by a specific key. I managed to do this but I then no longer have an array but some kind of an object.
Starting JSON data
[{
"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
}
]
This is my grouping code
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);
}
This is the output
{4: Array(3), 35: Array(1)}
The 4 and 35 is the user_ids. I would like them to get parts of an array so I can loop them, that I cannot do now.