How to separate values from a json response and sum your results?

0

I have the following AJAX response:

[{"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 split into two arrays, with valor adding to dt_month .

Expected result:

arr1=[11, 9, 5];
arr2=[250, 1324.50, 12.35];
    
asked by anonymous 30.11.2017 / 17:30

1 answer

0

Would not it be better to create an object with the keys each month? 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 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"]);
}
    
30.11.2017 / 17:42