根据对象的整体键合并对象数组 [duplicate]

Merge array of objects based on overall key of object [duplicate]

提问人:Mohamed Khalifa 提问时间:9/25/2023 更新时间:9/25/2023 访问量:35

问:

我有这个对象数组

var worksSummaryDetailsArr = [
  {
    year: 2020,
    worksSummaryDetailsObj: [ [Object], [Object], [Object], [Object] ]
  },
  {
    year: 2021,
    worksSummaryDetailsObj: [ [Object], [Object], [Object], [Object] ]
  },
  {
    year: 2022,
    worksSummaryDetailsObj: [ [Object], [Object], [Object], [Object] ]
  },
  {
    year: 2021,
    worksSummaryDetailsObj: [ [Object], [Object], [Object], [Object] ]
  },
  {
    year: 2022,
    worksSummaryDetailsObj: [ [Object], [Object], [Object], [Object] ]
  }
]

我想将它合并到


  {
    year: 2020,
    worksSummaryDetailsObj: [ [Object], [Object], [Object], [Object] ]
  },
  {
    year: 2021,
    worksSummaryDetailsObj: [ [Object], [Object], [Object], [Object],[Object], [Object], [Object], [Object] ]
  },
  {
    year: 2022,
    worksSummaryDetailsObj: [ [Object], [Object], [Object], [Object],[Object], [Object], [Object], [Object] ]
  },

我尝试使用设置函数并映射相同的年份,并且输出是相同的年份被正确合并,但 worksSummaryDetailsObj 包含错误的数据

这是我的代码


const r = [...new Set(worksSummaryDetailsArr.map((i) => i.year))].map((i) => ({
      year: i,
      worksSummaryDetailsObj: [...new Set(worksSummaryDetailsArr.filter(({ year: c }) => c === i))],
}));

console.log(r);
JavaScript 数组 JSON 对象

评论

0赞 Mark Schultheiss 9/25/2023
我链接了一些选项,但这已经被问过很多次了

答:

0赞 skmail 9/25/2023 #1

一个简单的reduce和数组合并就可以实现你想要的

Object.values(
  worksSummaryDetailsArr.reduce((acc, arr) => {
    if (!acc[arr.year]) {
      acc[arr.year] = arr;
    } else {
      acc[arr.year] = {
        ...acc[arr.year],
        worksSummaryDetailsObj: [
          ...acc[arr.year].worksSummaryDetailsObj,
          ...arr.worksSummaryDetailsObj,
        ],
      };
    }
    return acc;
  }, {})
);