如何根据key合并数组中的对象(已同步到npm lm-public-js 中)

项目中经常会遇到,array内包含object这个格式的json 需要我们根据一个key去合并其中的对象,一般是 id
效率最低的方法是 循环套循环,找到一致id的,然后添加到其中一个array内
比较好的方法 是把这个id对应的object 暂存一个obj内,比如 obj[item.id] = {…item,…item2}
最后根据 Object.values() 方法 重新转化为数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
function mergeArrAndObj(data1 = [],data2 = [],key){
if(!(data1 instanceof Array || data1 instanceof Object)) return console.warn('第一个参数格式不对')
if(!(data2 instanceof Array || data2 instanceof Object)) return console.warn('第二个参数格式不对')
if(!((data1 instanceof Array && data2 instanceof Array) || (data1 instanceof Object && data2 instanceof Object))) return console.warn('数据类型不一致')

//都为数组的情况
if( data1 instanceof Array){
if(typeof key !== 'string') return console.warn('第三个参数 key 应为字符串')
if(!key.length) return console.warn('第三个参数 key 长度不应为空')
if(typeof key === 'undefined') return console.warn('请传入第三个参数 key')

//找出最长的数组
let maxArr = data1.length > data2.length ? data1:data2
//找出最长的数组
let minArr = data1.length < data2.length ? data1:data2
//临时存放数据的数组
let sumArr = []
//临时存放数据的对象
let obj = {}

maxArr.forEach((item,index)=>{
//此时短的那一个数组已经循环完了
if(minArr[index] === undefined){
//只需要处理较长的那个数组
return obj[item[key]] = {...maxArr[index]}
}

//这里是短的那一个数组还没循环完的情况
obj[item[key]] = {...maxArr[index],...minArr[index]}
})
sumArr = Object.values(obj)

return sumArr

}else{
//都为对象
//此处为浅合并 key一致会被替换
return {...data1,...data2}
}

}

简单测试一下

1
2
3
4
5
6
mergeArrAndObj([{id:2,c:2}],[{id:2,a:2},{id:3,a:3}],'id')

[
{id:2,c:2,a:2},
{id:3,a:3}
]