如何将数组数据中的数组获取到角度7中的另一个数组

时间:2018-12-31 06:38:58

标签: arrays angular7

我有一个包含数组的json数据集。我想从该数据集中检索数据到另一个数组。

这是我的json数据

[
    {
        "user": [
            {
                "userActivityId": "08d66e8f-0f2f-3162-4d1d-b0307df0b532",
                "userId": "08d65df8-5a1c-4879-b8b6-f583bafa8084",
                "userName": "Dorothy",
                "photoUrl": "08d65df8-5a1c-d841-cff6-444e72fa08f2",
                "createdOn": "2018-12-31T01:13:23.363154",
                "itemType": 0,
                "itemId": "08d66e8f-0f2f-2efa-db7a-ab313ff89e7c"
            },
            {
                "userActivityId": "08d66e8f-19cf-7c9c-1e07-00c9e7c37fc0",
                "userId": "08d65df8-5a1c-4879-b8b6-f583bafa8084",
                "userName": "Dorothy",
                "photoUrl": "08d65df8-5a1c-d841-cff6-444e72fa08f2",
                "createdOn": "2018-12-31T01:13:41.190886",
                "itemType": 1,
                "itemId": "08d66e8f-19cf-a711-47a1-9690d9f6bf5e"
            }
        ]
    },
    {
        "user": [
            {
                "userActivityId": "08d66e3f-61e0-55db-f57d-5d434738d366",
                "userId": "08d6630e-325b-3474-5b5c-3c07af8063b8",
                "userName": "Supun",
                "photoUrl": "1",
                "createdOn": "2018-12-30T15:43:02.314203",
                "itemType": 0,
                "itemId": "08d66e3f-61df-c79d-dac4-f16f1142d526"
            }
        ]
    }
]

我想做的是,我想将此数据集放入用户数组值中,成为单个数组。

这是我遵循的方式,

friendsStufs: any[];
 this.userService.getFriendsStufs(this.authService.currentUser.id).subscribe(data => {
  data.forEach(user => {
    user.forEach(stufs => {
      this.friendsStufs.push(stufs);
    });
  });
}, error => {
  console.log(error);
  this.alertify.error('Can retrieve friends stufs');
});

1 个答案:

答案 0 :(得分:1)

您可以使用array#reduce在单个数组中累积所有用户对象。

let data = [ { "user": [ { "userActivityId": "08d66e8f-0f2f-3162-4d1d-b0307df0b532", "userId": "08d65df8-5a1c-4879-b8b6-f583bafa8084", "userName": "Dorothy", "photoUrl": "08d65df8-5a1c-d841-cff6-444e72fa08f2", "createdOn": "2018-12-31T01:13:23.363154", "itemType": 0, "itemId": "08d66e8f-0f2f-2efa-db7a-ab313ff89e7c" }, { "userActivityId": "08d66e8f-19cf-7c9c-1e07-00c9e7c37fc0", "userId": "08d65df8-5a1c-4879-b8b6-f583bafa8084", "userName": "Dorothy", "photoUrl": "08d65df8-5a1c-d841-cff6-444e72fa08f2", "createdOn": "2018-12-31T01:13:41.190886", "itemType": 1, "itemId": "08d66e8f-19cf-a711-47a1-9690d9f6bf5e" } ] }, { "user": [ { "userActivityId": "08d66e3f-61e0-55db-f57d-5d434738d366", "userId": "08d6630e-325b-3474-5b5c-3c07af8063b8", "userName": "Supun", "photoUrl": "1", "createdOn": "2018-12-30T15:43:02.314203", "itemType": 0, "itemId": "08d66e3f-61df-c79d-dac4-f16f1142d526" } ] } ],
    result = data.reduce((r,{user}) => {
      user.forEach(o => r.push({...o}));
      return r;
    },[]);
console.log(result);