数组中子元素通过某个相同字段将子元素中相同的字段放入一个对象内且子元素中的子数组完成合并
案例如下
let list = [
{
defineCode: "001",
defineName: "分级名称1",
gradeType: "分级类型1",
orgVos: [
{
orgCode: "组织编码1",
orgName: "组织名称1",
},
],
},
{
defineCode: "001",
defineName: "分级名称1",
gradeType: "分级类型1",
orgVos: [
{
orgCode: "组织编码2",
orgName: "组织名称2",
},
],
},
{
defineCode: "002",
defineName: "分级名称2",
gradeType: "分级类型2",
orgVos: [
{
orgCode: "组织编码2",
orgName: "组织名称2",
},
],
},
];
const mergedList = list.reduce((acc, curr) => {
const existingItem = acc.find(item => item.defineName === curr.defineName);
if (existingItem) {
existingItem.orgVos = [...existingItem.orgVos, ...curr.orgVos];
} else {
acc.push(curr);
}
return acc;
}, []);
console.log(mergedList)
打印内容如下
相关文章