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
}

聲明:此博客為個人學習之用,如與其他作品雷同,純屬巧合,並請明示指出


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM