How to separate values from a json answer and add their results?

Asked

Viewed 106 times

0

I have the following reply from AJAX:

[{"valor":"100","dt_month":"11"},
 {"valor":"150","dt_month":"11"},
 {"valor":"1324.50","dt_month":"9"},
 {"valor":"12.35","dt_month":"5"}]`

I would like to separate into two arrays, being that the valor sum according to the dt_month.

Expected result:

arr1=[11, 9, 5];
arr2=[250, 1324.50, 12.35];

1 answer

0


Wouldn’t it be better to create an object with each month’s keys? Something like this:

let json = [{"valor":"100","dt_month":"11"},
            {"valor":"150","dt_month":"11"},
            {"valor":"1324.50","dt_month":"9"},
            {"valor":"12.35","dt_month":"5"}]

let result = {};
for(var i of json){
    if(!(i["dt_month"] in result)){
        result[i["dt_month"]] = 0;
    }
    result[i["dt_month"]] += parseFloat(i["valor"]);
}

In this case, to access the values just put result["<valor_do_mês>"].

If you really want to do it with two vectors, it should look like this:

let json = [{"valor":"100","dt_month":"11"},
        {"valor":"150","dt_month":"11"},
        {"valor":"1324.50","dt_month":"9"},
        {"valor":"12.35","dt_month":"5"}]

let dates = [];
let sums = [];
for(var i of json){
     if(dates.indexOf(i["dt_month"]) < 0){
        dates.push(i["dt_month"]);
        sums.push(0);
    }
    sums[dates.indexOf(i["dt_month"])] += parseFloat(i["valor"]);
}
  • 1

    Thank you very much! I got the result I wanted. NOTE: for the non-integer values I only changed parseint to parseFloat.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.