首页 > 解决方案 > es6 将两个数组与对象合并并累积数据

问题描述

我有两个对象数组

const a = [
  {
    "categoryId": 1,
    "categoryName": "category 1",
    "id": 11
  },
  {
    "categoryId": 2,
    "teamName": "category 2",
    "id": 22
  }
]

const b = [
  {
    "categoryId": 2,
    "categoryName": "category 2",
    "id": 33
  },
  {
    "categoryId": 3,
    "categoryName": "category 3",
    "id": 44
  }
]

现在我想将它们合并在一起,最终结果应该如下所示:

const result = [
  {
    "categoryId": 1,
    "categoryName": "category 1",
    "aId": 11,
    "bId" null: 
  },
  {
    "categoryId": 2,
    "categoryName": "category 2",
    "aId": 22,
    "bId" 33:
  },
  {
    "categoryId": 3,
    "categoryName": "category 3",
    "aId": null,
    "bId" 44:
  }
]

我看不到如何分配空值。

我已经用 Object.assign 和 "..." 运算符尝试过,但没有得到想要的结果。

同样,我想根据数组将 id 重命名为新键。

let result = a.concat(b) 会给我一个错误的结果

标签: javascriptecmascript-6

解决方案


您可以使用contat()将数组合并在一起,然后reduce()通过其键删除重复的对象:

    const admin = [
      {
        "categoryId": 66,
        "categoryName": "category 66",
        "id": 204
      },
      {
        "categoryId": 149,
        "teamName": "category 149",
        "id": 178
      }
    ]

    const member = [
      {
        "categoryId": 66,
        "teamName": "category 66",
        "id": 271
      },
      {
        "categoryId": 68,
        "teamName": "category 68",
        "id": 264
      }
    ];
    
    const client = [
      {
        "categoryId": 66,
        "teamName": "category 66",
        "id": 271
      },
      {
        "categoryId": 155,
        "teamName": "no team",
        "id": 264
      }
    ];
    const merge = function(...params) {
        let mergeResult = [];
        params.map(elem => {mergeResult = mergeResult.concat(elem); });
        return mergeResult;
    }

    const result = Object.values(merge(member, admin, client).reduce((acc,cur)=>Object.assign(acc,{[cur.categoryId]:cur}),{}));

    console.log(result);

如果您需要更改重复的过滤条件,只需cur.categoryIdObject.assign()函数中更改


推荐阅读