How to add attribute in JSON array?

1

I have the following JSON:

[{"descricao": "teste",
"January": "2454.00",
"February": "220.00",
"March": "1070.25"}, {
"descricao": "teste2",
"January": "275.00"}, {
"descricao": "teste3",
"January": "275.00"}]

I need to record in a variable the sum of the months:

  • January: total
  • February: total
  • March: total
  • How can I do this?

        
    asked by anonymous 24.03.2017 / 12:40

    2 answers

    2

    You have to scroll through this array and add the numbers (converting them to Number ) and, for example, creating an object with the result:

    var dados = [{
      "descricao": "teste",
      "January": "2454.00",
      "February": "220.00",
      "March": "1070.25"
    }, {
      "descricao": "teste2",
      "January": "275.00"
    }, {
      "descricao": "teste3",
      "January": "275.00"
    }];
    var somador = {};
    dados.forEach(function(dado) {
      Object.keys(dado).forEach(function(prop) {
        if (prop == 'descricao') return;
        if (!somador[prop]) somador[prop] = 0;
        somador[prop] += Number(dado[prop]);
      });
    });
    
    alert(JSON.stringify(somador, 4, '\t'));
        
    24.03.2017 / 12:45
    1

    A different way:

    var json = [{"descricao": "teste",
    "January": "2454.00",
    "February": "220.00",
    "March": "1070.25"}, {
    "descricao": "teste2",
    "January": "275.00"}, {
    "descricao": "teste3",
    "January": "275.00"}];
    
    var total = {
      "January": 0,
      "February": 0,
      "March": 0
    };
    
    for(j in json) {
       total['January'] += Number(json[j]['January']) | 0;
       total['February'] += Number(json[j]['February']) | 0;
       total['March'] += Number(json[j]['March']) | 0;
    }
    
    console.log(total);
        
    24.03.2017 / 12:56