Add values from a JSON array

2

I have this JSON array:

[{"amount":"500"},{"amount":"750"},{"amount":"250"}]

I have tried to add the values it contains with:

$.getJSON('http://api.com..../water.php',function(data_water_tot){
console.log(data_water_tot);
 $.each(data_water_tot,function(){
    total += data_water_tot[cont].amount;
 });
 console.log(total);
});

I do not know how to add 400 + 750 + 250.

    
asked by Kiku S. 26.05.2017 в 16:42
source

3 answers

0

I have already solved the problem, so, in case someone is interested:

$.getJSON('http://api.com..../water.php',function(data_water_tot){
    cont=0;
    total=0;
    console.log(data_water_tot);
     $.each(data_water_tot,function(){
        valor = parseInt(data_water_tot[cont].amount);
        cont++;
        total = total+valor;
     });
     console.log(total); 
});
    
answered by 26.05.2017 / 17:05
source
3

It does not add up because you do not have a variable cont within each, I suggest you make these changes in the function of .each() :

function(pos, elemento){
  total += elemento.amount;
}

the variable pos is an index of the position of the array, elemento is the object that is in an array position, which is no longer necessary to have the array and indicate the position to query.

It should look like this:

$.getJSON('http://api.com..../water.php',function(data_water_tot){
  console.log(data_water_tot);
  $.each(data_water_tot,function(pos, elemento){
    total += elemento.amount;
  });
  console.log(total);
});
    
answered by 26.05.2017 в 16:57
2

Arrays in JavaScript have the forEach method, which accepts each array value as an argument. Within each call, you can add the value of each item.

data_water_tot = [{"amount":"500"},{"amount":"750"},{"amount":"250"}];
console.log(data_water_tot);
var total = 0;
data_water_tot.forEach(function (obj) {
    total += parseInt(obj.amount);
});
console.log(total);
    
answered by 26.05.2017 в 19:55