Summing up JSON values

Asked

Viewed 597 times

0

I’m starting to mess with JSON and Javascript and have the following AJAX:

   $.ajax({
        url: 'https://...',
        type: 'POST',
        dataType: 'json',
        data: 'inpnomeRequisitante=' + 'XXXXXXXXXX',
        success: function (data) {
            var fluxosAndamento = "";
            var fluxosSolicitadosAnoCorrente = "";
            var valor = 0;
            $.each(data.success, function (i, item) {}});

This AJAX returns the values exactly like this:

{
  "success": [
    {
     "fields": {
        "Valor": "22,33",
      }
    },
    {
      "fields": {
        "Valor": "146,33",
      }
    }
  ],
  "cache": false,
  "datasource": 2166,
  "runtime": 63,
  "bytes": 2369
}

I would like to know how it is possible to sum all the returned values of data.success[i].fields.Valor, as in this example: 22,33 + 146,33 + VALOR XXXX (if it has more values)... And how can I replace the "," to the "." at each of these values within the $each so that they can be summed since Javascript does not accept "10,00" and yes "10.00".

  • Your JSON is not valid. Are you sure that’s how it is?

  • Yeah, I didn’t put it here at a url or the date I’m going through. However, it returns the data exactly as it is there: "Value": "146,33", "Value": "22,33",

  • So if it is exactly as it is there, it is not a valid JSON, there is no way to analyze it with JS. It seems that there is a wrong brackets on line 13 that perhaps should not exist.

  • Sorry @Andersoncarloswoss! Exactly, this bracket does not exist there. You would know how to take the value of each date.?

  • Please edit the question by adding valid JSON so we can help you more easily.

3 answers

1

You can use a simple repeat loop for:

const data = {
  success: [
    {
      cod: '158877',
      txt: '158877',
      fields: {
        Valor: '22,32',
        Resultado_Instância: 'Solicitação Encaminhada',
        Status: 'Em Andamento',
        Data_Inicio: '13/06/2019 17:22:11'
      }
    },
    {
      cod: '157744',
      txt: '157744',
      fields: {
        Valor: '146,32',
        Resultado_Instância: 'Solicitação Encaminhada',
        Status: 'Em Andamento',
        Data_Inicio: '12/06/2019 17:22:11'
      }
    }
  ],
  cache: false,
  datasource: 2166,
  runtime: 63,
  bytes: 2369
};

let sum = 0;

for (const item of data.success) {
  sum += parseFloat(item.fields.Valor.replace(/\./g, '').replace(/,/, '.'));
}

console.log(sum);

However, if you want to go for a slightly more sophisticated path, you can also use approaches that make use of the reduce:

const data = {
  success: [
    {
      cod: '158877',
      txt: '158877',
      fields: {
        Valor: '22,32',
        Resultado_Instância: 'Solicitação Encaminhada',
        Status: 'Em Andamento',
        Data_Inicio: '13/06/2019 17:22:11'
      }
    },
    {
      cod: '157744',
      txt: '157744',
      fields: {
        Valor: '146,32',
        Resultado_Instância: 'Solicitação Encaminhada',
        Status: 'Em Andamento',
        Data_Inicio: '12/06/2019 17:22:11'
      }
    }
  ],
  cache: false,
  datasource: 2166,
  runtime: 63,
  bytes: 2369
};

const sum = data.success.reduce(
  (acc, current) =>
    acc + parseFloat(current.fields.Valor.replace(/\./g, '').replace(/,/, '.')),
  0
);

console.log(sum)

Recommended reading:

  • Thanks Luiz! I will test the functions you gave me here!

  • It worked! Thank you very much!

0

Luiz’s answer already meets your question, I’ll just leave another example of how it can be done using reduce:

const dados = {
  success: [
    {
      cod: "158877",
      txt: "158877",
      fields: {
        Valor: "22,33",
        Resultado_Instância: "Solicitação Encaminhada",
        Status: "Em Andamento",
        Data_Inicio: "13/06/2019 17:22:11"
      }
    },
    {
      cod: "157744",
      txt: "157744",
      fields: {
        Valor: "146,33",
        Resultado_Instância: "Solicitação Encaminhada",
        Status: "Em Andamento",
        Data_Inicio: "12/06/2019 17:22:11"
      }
    }
  ],
  cache: false,
  datasource: 2166,
  runtime: 63,
  bytes: 2369
};
 
let valores = [];       // array para armazenar os valores pegos com um map()
  
dados.success.map(x => {
  valores.push(x.fields.Valor);
})
  
console.log(valores);
  
let soma = valores.reduce((a, b) => {       // método que faz a soma
  return parseFloat(a) + parseFloat(b);     // converte de string para number
})
  
console.log(soma.toFixed(2));    // deixa com apenas 2 casas decimais

  • Show! I will study a little more about reduce! Thank you!!!

0

You have to treat that string so it can be converted to Number, then you have to add the values.

An example would be:

const dados = {
  success: [{
      cod: "158877",
      txt: "158877",
      fields: {
        Valor: "22,33",
        Resultado_Instância: "Solicitação Encaminhada",
        Status: "Em Andamento",
        Data_Inicio: "13/06/2019 17:22:11"
      }
    },
    {
      cod: "157744",
      txt: "157744",
      fields: {
        Valor: "146,33",
        Resultado_Instância: "Solicitação Encaminhada",
        Status: "Em Andamento",
        Data_Inicio: "12/06/2019 17:22:11"
      }
    }
  ],
  cache: false,
  datasource: 2166,
  runtime: 63,
  bytes: 2369
};

const values = dados.success.map(obj => {
  const valueString = obj.fields.Valor.replace(/,/, '.');
  return Number(valueString);
});
const sum = values.reduce((total, nr) => total + nr, 0);


console.log(sum.toFixed(2)); // 168.66

Browser other questions tagged

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