1、需求
數組對象中相同屬性值求和,(數值相加,數組重組)
2、案例
let a=[{
"id": 1,
"sahib": 1,
"child": 2,
"age": [3,1],
"index": 0
},{
"sahib": 2,
"age": [],
"child": 0,
"id": 2
}
]
let res = a.reduce((result, next)=>{
if(!result) result = {}
Object.keys(next).forEach((key)=>{
//數值類型
if(typeof next[key] == 'number'){
result[key] = (result[key]?result[key]:0) + next[key]
}
//數組類型
if(next[key] instanceof Array){
result[key] = (result[key]?result[key]:[]).concat(next[key])
}
})
return result
})
console.log(res)
//結果
{
age: [3, 1],
child: 2,
id: 3,
index: 0,
sahib: 3
}
聲明:此博客為個人學習之用,如與其他作品雷同,純屬巧合,並請明示指出