The same key in the array of js objects, and the value values are added

var arry= [
    {key:"a",value:2},
    {key:"a",value:2},
    {key:"a",value:2},
    {key:"b",value:8}
]

expect results:

var newArr =[
    {key:"a",value:6},
    {key:"b",value:8}
]
Mar.04,2021

this is basically the same logic as the one just now. Why don't you just change it a little bit?

var obj = {};
arr.forEach(function(value){
    var id = value.id,
        num = value.num ;
    if(obj.hasOwnProperty(id)){
       // var cur = obj[id].num;
       // obj[id].num = Math.max(cur, num) ;
       obj[id].num += num
    }else{
        obj[id] = {
            'id' : id,
            'num' : num
        }
    }
})
console.log(Object.values(obj))


var arry= [

        {key:'a',value:2},
        {key:'a',value:2},
        {key:'a',value:2},
        {key:'b',value:8}
    ]
    let target = [];
    let keysArr =[...new Set( arry.map(item=>item.key))]  ;

    keysArr.forEach(item=>{
       const  arr = arry.filter(keys=>keys.key == item);
       const sum = arr.reduce((a,b)=>a+b.value,0)
        target.push({
            key:item,
            value:sum
        })
    })
    console.log(  target )
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b38832-4ed84.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b38832-4ed84.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?