js合并对象数组相同项,并对另一属性做累加处理

例子:合并日期相同的数据,数据为空时,补0。

var data = [{ bzmc: "品牌1", hyrq: "2023-06-07", hyxm: "11", hyjg: "3" },
    { bzmc: "品牌2", hyrq: "2023-06-07", hyxm: "11", hyjg: "2" },
    { bzmc: "品牌3", hyrq: "2023-06-08", hyxm: "22", hyjg: "12.4" },
    { bzmc: "品牌4", hyrq: "2023-06-08", hyxm: "22", hyjg: "45.1" }, { bzmc: "品牌5", hyrq: "2023-06-13", hyxm: "33", hyjg: "12" },
    { bzmc: "品牌6", hyrq: "2023-06-14", hyxm: null, hyjg: null }]
let newArray=data.reduce((total,cur,index)=>{
        let i=total.findIndex(current=>current.hyrq===cur.hyrq)
        cur.hyjg=cur.hyjg*1
        if(cur.hyjg===null){
            cur.hyjg=0
        }
        i===-1&&total.push(cur)
        i!==-1&&(total[i].hyjg=total[i].hyjg*1+cur.hyjg*1)
        return total
},[])

看一下输出结果:

猜你喜欢

转载自blog.csdn.net/qq_44774622/article/details/131539372