Sum the same object of array

前端 未结 4 843
[愿得一人]
[愿得一人] 2021-01-25 09:09
var data = [ {id:1, qty:100}, {id:2, qty:200}, {id:1, qty:100}, {id:2, qty:200} ];

How to sum this array become to [ {id:1, qty:200}, {id:2, qty:

4条回答
  •  半阙折子戏
    2021-01-25 09:54

    Try this:

    var sum = [];
    
    data.forEach(function(o) {
        var existing = sum.filter(function(i) { return i.id === o.id })[0];
    
        if (!existing)
            sum.push(o);
        else
            existing.qty += o.qty;
    });
    

    See Fiddle

提交回复
热议问题