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

前端 未结 4 1488
南方客
南方客 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:55

    When you're looping over the objects, see what taxId it is and generate a sum for each different taxId.

    var sums = {}, obj, i;
    for (i = 0; i < selected_taxes.length; i++){
        obj = selected_taxes[i];
        if (!sums[obj.tax_id]) {
            sums[obj.tax_id] = 0;
        }
        sums[obj.tax_id] += +obj.tax_value;
    }
    console.log(sums); //{ 1:26.46, 2:34.39, 3: 52.76}
    

    http://jsfiddle.net/4X6Wb/

提交回复
热议问题