let arr1 = [
{id: '1', test: '1'},
{id: '2', test: '2'},
{id: '3', test: '3'},
{id: '4', test: '4'}
]
let arr2 = [
{id: '1', test2: '1'},
{id: '2', test2: '2'},
{id: '3', test2: '3'},
{id: '5', test2: '5'}
]
let arr3 = [
{id: '1', test2: '1'},
{id: '2', test2: '2'},
{id: '3', test2: '3'},
{id: '6', test2: '6'}
]
let arr4 = [
{id: '1', test2: '1'},
{id: '2', test2: '2'},
{id: '3', test2: '3'},
{id: '7', test2: '7'}
]
let arrList = [arr1,arr2,arr3,arr4]
// 欲合并后得到如下数组:
// [
// {id: '1', test: '1',test2: '1'},
// {id: '2', test: '2', test2: '2'},
// {id: '3', test: '3', test2: '3'},
// {id: '4', test: '4'},
// {id: '5', test2: '5'},
// {id: '6', test2: '6'},
// {id: '7', test2: '7'}
// ]
function ArrayAssign(arg1,arg2,id){
let obj = new Object()
let arr_copy1 = []
let arr_copy2 = []
// 在下面的遍历中,若arg1为空数组,则不能合并。
// 故先判断,预防空数组出现,长度更长者在外层。
if(arg1.length >= arg2.length){
arr_copy1 = arg1
arr_copy2 = arg2
} else {
arr_copy1 = arg2
arr_copy2 = arg1
}
arr_copy1.forEach((item)=>{
obj[item[id]] = item
arr_copy2.forEach((item2)=>{
if(item2[id] == item[id]){
obj[item[id]] = Object.assign(item,item2)
} else {
if(!obj.hasOwnProperty(item2[id])){
obj[item2[id]] = item2
}
}
})
})
return Object.values(obj)
}
let all = arrList.reduce((prev,cur,index,arr3) => { // 前一项、当前项、下标、数组名
return ArrayAssign(prev, cur,'id');// 传入要合并的数组,和两个数组元素中都唯一的键
})
console.log(all)
JS合并多个对象数组
于 2022-06-28 15:51:44 首次发布