Browse json array object

2

I have the following json:

[{titulo : "Total", balesia : 1, torre:2, CT:3, HF :6}, {titulo : "Total", balesia : 4, torre:2, CT:5, HF :8} ]

I need to go through it and add only those that have a numerical value and store it in another object.

How to traverse this json object and add the numerical values to store the result of the sum in another object?

I'm not that good at javascript.

    
asked by cristian gonzalez 15.11.2016 в 18:50
source

3 answers

4

Answer if you do not know the type of data that you have inside the object:

    let res = 0;
    let a = [
         {titulo : "Total", balesia : 1, torre:2, CT:3, HF :6}, 
         {titulo : "Total", balesia : 4, torre:2, CT:5, HF :8}
    ];

    /**
     * Ésto lo resuelve
     */
    a.forEach((e)=>{
                     for(var p in e){
                       typeof e[p] == "number" && (res+=e[p]);
                     }
                   }
    );

    console.log("Resultado: " + res);

With this you only add up those that are numbers, no matter what variables the object has. Hope this can help you! Greetings.

    
answered by 15.11.2016 в 21:54
2
var tuJSON = [{titulo : "Total", balesia : 1, torre:2, CT:3, HF :6}, {titulo : "Total", balesia : 4, torre:2, CT:5, HF :8} ];
var retorno = 0;
tuJSON.forEach(function(currentValue,index,arr) {
    retorno += currentValue.balesia + currentValue.torre + currentValue.CT + currentValue.HF;
});
console.log(retorno);
    
answered by 15.11.2016 в 19:02
2

You can use Array.reduce () to get the object

var arr = [
  {
    titulo : "Total", 
    balesia : 1, 
    torre:2, 
    CT:3, 
    HF :6
  }, 
  {
    titulo : "Total", 
    balesia : 4, 
    torre:2, 
    CT:5, 
    HF :8
  } 
]


var res = arr.reduce(function(anterior,actual){
  return {
    balesia: anterior.balesia   + actual.balesia,
    torre: anterior.torre   + actual.torre,
    CT: anterior.CT   + actual.CT,
    HF: anterior.HF   + actual.HF
  }
},{
  balesia:0,
  torre:0,
  CT:0,
  HF:0
})
console.log(res);

Reduce takes two parameters:

  • Function that takes the previous value and the current value of the array
  • Initial value (is passed to the function as the previous value for the first element)
  • and return the object directly;

    When starting Reduce with an object with the properties that we want, we can add each property of the array and obtain a new object with its properties equal to the sum of the properties of each element of the array

    For more information about Reduce

        
    answered by 15.11.2016 в 19:44