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

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

    Use the reduce method:

    selected_taxes.reduce(function (p, c) {
        if (p[c["tax_id"]]) {
            p[c["tax_id"]]["total_tax"] += +c["tax_value"];
        } else {
            p[c["tax_id"]] = {
                "tax_name": c["tax_name"],
                "total_tax": +c["tax_value"]
            }
        }
        return p;
    }, {});
    

    This returns a new object containing the desired data:

    {
        "1": {
            "tax_name": "GST 5%",
            "total_tax": 26.46
        },
        "2": {
            "tax_name": "HST 13%",
            "total_tax": 34.39
        },
        "3": {
            "tax_name": "QST 9.975%",
            "total_tax": 52.76
        }
    }
    

    DEMO

提交回复
热议问题