How to add attribute in JSON array?

Asked

Viewed 863 times

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"}]

inserir a descrição da imagem aqui

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

  1. January: total
  2. February: total
  3. March: total

How can I do that?

2 answers

2


You have to go through this array and add the numbers (converting these strings 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'));

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);

Browser other questions tagged

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