假设有两组数组,其中的对象有一个指定的属性一致,根据一样的属性进行合并
let a = [{name:1,title:1},{name:2,title:2}]
let b = [{name:1,src:3},{name:2,src:3}]
let c= [...a,...b];
let dd =c.reduce((prev,next)=>{//reduce中return的元素会作为prev继续使用
prev[next.name]?prev[next.name]={...next,...prev[next.name]}:prev[next.name]={...next}
return prev
},{})
console.log(Object.values(dd))
reduce的参考用法:
var arrString = 'abcdaabc';
arrString.split('').reduce(function(res, cur) {
res[cur] ? res[cur] ++ : res[cur] = 1
return res;
}, {})