JavaScript: How can I add the numerical elements inside a json?

0

Good morning everyone, my query is the following ... If I have a JSON object in javascript, for example:

json = [{"Nombre":"Sutano","Edad":19},{"Nombre":"Fulano","Edad":20},{"Nombre":"Mengano","Edad":21}];

And I want to add only the numerical values within each element, in this case, the age, how could I do it?

    
asked by Josue 09.11.2018 в 23:03
source

3 answers

1

In this case, you should use reduce , taking the opportunity to verify, before adding, that the value in Edad is numeric. If you make an innocent sum without verification, and by mistake there is a non-numeric value, the total result will be NaN . Or, if the number is in quotes, it will be added to the total amount so far, producing totally unlikely results.

This code would avoid that.

The evaluation is done here: typeof value.Edad == "number" ? sum + value.Edad : sum using a ternary operator.

var json = '[{"Nombre":"Sutano","Edad":19},{"Nombre":"Fulano","Edad":20},{"Nombre":"Mengano","Edad":21}]';

/*Convertimos la cadena a un array json*/
var arr = JSON.parse(json);

var totalAges = arr.reduce((sum, value) => (typeof value.Edad == "number" ? sum + value.Edad : sum), 0);
console.log(totalAges);

Let's try a possible wrong value:

var json = '[{"Nombre":"Sutano","Edad":19},{"Nombre":"Fulano","Edad":"Veinte"},{"Nombre":"Mengano","Edad":21},{"Nombre":"Sutana","Edad":"199999"}]';

/*Convertimos la cadena a un array json*/
var arr = JSON.parse(json);

var totalAges = arr.reduce((sum, value) => (typeof value.Edad == "number" ? sum + value.Edad : sum), 0);
console.log(totalAges);

Let's see a code without verification:

Right here:

var json = '[{"Nombre":"Sutano","Edad":19},{"Nombre":"Fulano","Edad":20}]';

/*Convertimos la cadena a un array json*/
var arr = JSON.parse(json);

var totalAges = arr.reduce((sum, value) => ( sum + value.Edad ), 0);
console.log(totalAges);

Here not so good anymore:

var json = '[{"Nombre":"Sutano","Edad":19},{"Nombre":"Fulano","Edad":"veinte"}]';

/*Convertimos la cadena a un array json*/
var arr = JSON.parse(json);

var totalAges = arr.reduce((sum, value) => ( sum + value.Edad ), 0);
console.log(totalAges);

Here you can be put in jail if it is to add the total of an account :):

var json = '[{"Nombre":"Sutano","Edad":19},{"Nombre":"Fulano","Edad":"20"}]';

/*Convertimos la cadena a un array json*/
var arr = JSON.parse(json);

var totalAges = arr.reduce((sum, value) => ( sum + value.Edad ), 0);
console.log(totalAges);
    
answered by 10.11.2018 в 01:03
0

What you have here is an arrangement of objects json in your case you have to pass the entire arrangement javascript to json , I'll give you an example;

//Arreglo javascript de objetos json
let json = [{"Nombre":"Sutano","Edad":19},{"Nombre":"Fulano","Edad":20},{"Nombre":"Mengano","Edad":21}];
//convirtiendo a json
json = JSON.stringify(json);
//Convirtiendo a objeto javascript
let data = JSON.parse(json);
var suma= 0;
//Recorriendo el objeto
for(let x in data){
  suma += data[x].Edad;//Ahora que es un objeto javascript, tiene propiedades
}

console.log('las edades suman: ' + suma);

At the end of the variable suma contains the sum of the ages, you must take into account the first thing I mention, which is that you have a fix javascript of objects json not a pure json for it I had to convert to json what I already had the variable json

    
answered by 09.11.2018 в 23:17
0

Good morning, this is my first response on this platform.

After analyzing the response of Albert Hidalgo, it made a lot of fun So I started to investigate and I think this does the same but it's simpler:

var suma=0;
var json = [
        {"Nombre":"Sutano","Edad":19},
        {"Nombre":"Fulano","Edad":20},
        {"Nombre":"Mengano","Edad":21}
       ];

/*como la variable json ya esta en un formato valido, con el que tienes un arreglo 
como json, no es necesario convertirlo, con lo cual solo lo recorres y accedes al 
elemento que te interesa
*/
json.forEach(function(elemento, indice) {
    suma += elemento["Edad"];
});
console.log('las edades suman: ' + suma);

note: the solution is correct, I comment any comments with my comment, greetings

    
answered by 10.11.2018 в 00:28