JS sum JSON value based on date month

JSON Data:

{
"client 1": [
    {
        "customer_branch_id": 128,
        "date": "2020-11-15",
        "total_after_tax": 174060
    },
    {
        "customer_branch_id": 128,
        "date": "2020-11-07",
        "total_after_tax": 94904
    }
],
"client 2": [
    {
        "customer_branch_id": 127,
        "date": "2020-11-16",
        "total_after_tax": 128160
    },
    {
        "customer_branch_id": 127,
        "date": "2020-11-07",
        "total_after_tax": 82320
    }
]

}

I am trying to sum total_after_tax data based on month from data field.

Also I want to set total_after_tax value to 0 if month doesn’t exist.

For example for client 1:

{
"client 1": [
    {
        "customer_branch_id": 128,
        "date": "1",
        "total_after_tax": 0
    },{
        "customer_branch_id": 128,
        "date": "2",
        "total_after_tax": 0
    },{
        "customer_branch_id": 128,
        "date": "3",
        "total_after_tax": 0
    },{
        "customer_branch_id": 128,
        "date": "4",
        "total_after_tax": 0
    },{
        "customer_branch_id": 128,
        "date": "5",
        "total_after_tax": 0
    },{
        "customer_branch_id": 128,
        "date": "6",
        "total_after_tax": 0
    },{
        "customer_branch_id": 128,
        "date": "7",
        "total_after_tax": 0
    },{
        "customer_branch_id": 128,
        "date": "8",
        "total_after_tax": 0
    },{
        "customer_branch_id": 128,
        "date": "9",
        "total_after_tax": 0
    },{
        "customer_branch_id": 128,
        "date": "10",
        "total_after_tax": 0
    },{
        "customer_branch_id": 128,
        "date": "11",
        "total_after_tax": 268964
    },{
        "customer_branch_id": 128,
        "date": "12",
        "total_after_tax": 0
    }
]

}

All months total_after_tax=0 except date=11 because its the only month that have result.

27 thoughts on “JS sum JSON value based on date month”

Leave a Comment