js 数组对象中相同属性值求和,(数值相加,数组重组)

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
}

声明:此博客为个人学习之用,如与其他作品雷同,纯属巧合,并请明示指出

原文地址:https://www.cnblogs.com/liliy/p/14921747.html