我正在構建一個 Angular 7 應用程序。在這個應用程序中,我從服務器獲取 JSON 數(shù)據(jù),然后我想按特定鍵對其進行分組。我設法做到了這一點,但我不再有數(shù)組而是某種對象。啟動 JSON 數(shù)據(jù)[{ "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},}]這是我的分組代碼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。我希望他們獲取數(shù)組的一部分,以便我可以循環(huán)它們,而我現(xiàn)在不能這樣做。
將 JSON 數(shù)據(jù)數(shù)組分組到另一個數(shù)組
繁華開滿天機
2021-10-21 16:06:21