猿问

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

我正在构建一个 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

},

}

]


这是我的分组代码


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。我希望他们获取数组的一部分,以便我可以循环它们,而我现在不能这样做。


繁华开满天机
浏览 209回答 2
2回答
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答