js merges the same items in the object array, and adds up another attribute

Example: Merge data with the same date, when the data is empty, fill with 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
},[])

Take a look at the output:

 

Guess you like

Origin blog.csdn.net/qq_44774622/article/details/131539372