对象数组 根据指定的属性 进行分组合并

let arr1 = [
        { type:1, name:"", age:"", num:"a" },
        { type:2, name:"", age:"", num:"b" },
        { type:3, name:"", age:"", num:"c" },
        { type:4, name:"", age:"", num:"d" }
];
let arr2 = [
        { type:1, name:"1", age:"45" },
        { type:3, name:"2", age:"4" },
        { type:2, name:"4", age:"4" },
        { type:4, name:"5", age:"4" }
      ];
      
  // 根据 type属性对应,最终合并成
let endArr = [
    { type:1, name:"1", age:"45",num:"a" },
    { type:2, name:"2", age:"4", num:"b" },
    { type:3, name:"4", age:"4", num:"c" },
    { type:4, name:"5", age:"4", num:"d" }
]

我的思路,先把两个数组合成一个,变成一个分组问题,然后对同一组进行合并,最后对每一组的属性值进行重新赋值;

阅读 4.5k
2 个回答

指定属性是唯一的 key,可以这样做:

function mergeArr(prop, ...arr) {
    if (!prop || !arr) return [];

    const map = {};
    arr.forEach(item => {
        item.forEach(info => {
            if (!info) return;

            const id = info[prop];
            map[id] = {...map[id], ...info}
        })
    })

    return Object.keys(map).map(key => map[key])
}

let arr1 = [
        { type:1, name:"", age:"", num:"a" },
        { type:2, name:"", age:"", num:"b" },
        { type:3, name:"", age:"", num:"c" },
        { type:4, name:"", age:"", num:"d" }
];
let arr2 = [
        { type:1, name:"1", age:"45" },
        { type:2, name:"2", age:"4" },
        { type:3, name:"4", age:"4" },
        { type:4, name:"5", age:"4" }
      ];
let arr3 = [
        { type:1, name:"", age:"", num:"a" },
        { type:2, name:"", age:"", num:"b" },
        { type:9, name:"aaa", age:"3" },
        { type:4, name:"", age:"", num:"d" }
];
let arr4 = [
        { type:1, name:"", age:"", num:"a" },
        { type:2, name:"", age:"", num:"b" },
        undefined,
        { type:4, name:"", age:"", num:"d" }
];

mergeArr('type',arr1,arr2,arr3,arr4)

只是个合并罢了,一行代码解决

let o = arr1.map((v, i) => { return {...v, ...arr2[i]}})
console.log(o)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题