Loop through array of objects and return sum of each total values by object element id

前端 未结 4 1486
南方客
南方客 2021-01-14 22:03

I\'m calculating taxes for a very complicate invoicing approach. I can\'t explain the whole process but if you have questions I will answer as best as I can

4条回答
  •  有刺的猬
    2021-01-14 22:35

    I think Array.prototype.reduce will be your best bet for this:

    var totals = data.reduce(function(c,x){
        if(!c[x.tax_id]) c[x.tax_id] = {
            tax_name: x.tax_name,
            tax_id: x.tax_id, 
            total_tax: 0
        };
        c[x.tax_id].total_tax += Number(x.tax_value);
        return c;
    }, {});
    

    This approach generates an object that has, as its properties, the tax ID numbers. If you really want a flat array from that, you can convert that into an array after the fact:

    var totalsArray = [];
    for(var taxId in totals){
        totalsArray.push(totals[taxId]):
    }
    

    Demonstration: http://jsfiddle.net/3jaJC/1/

提交回复
热议问题