Running complex JSON structure with java Script

0

Hello,

I'm starting now in the javascript world, I would need help to go through the following json structure:

Ineedto,forexample,incrementacounterwhenthe"win" field is set to "true", I need to store the value contained in certain fields as the "gameType" field in variables.

My (incorrect) Json looks like this:

  for(i in json.games) 
    {    
        for (j in json.games[i].stats)
        {
            if (json.games[i].stats[j].win === true)
            {    
                console.log(json.games[i].stats[j]);
            }
        }    
    }

Thank you in advance.

    
asked by anonymous 28.05.2016 / 16:14

1 answer

1

It does not take so many iterations. In fact, it is only necessary to iterate json.games .

Since the json.games variable is an array, the best way to iterate it is with the forEach() method (currently, there are faster solutions to iterating an array, but whereas forEach() is a native method of it is safer and more comfortable besides the browser itself iterate, giving more freedom in the use of the machine) that is native to the whole array, the specification of forEach() is relatively new, but already has 95% of implementation in the world's browsers and 97% of implementation in Brazil , so you can use it quietly.

A specification of forEach() summarized:

var foo = [3, 4, "bar"];

foo.forEach(function(elemento, indice, arrayCompleta){
  console.log(elemento, indice, arrayCompleta);
});

// Console:
// 3, 0, [3, 4, "bar"]
// 4, 1, [3, 4, "bar"]
// "bar", 2, [3, 4, "bar"]

Another problem in your code is that you iterated the properties too, since the properties always have a fixed name (for example, json.games[0].stats.win ), it is not necessary to iterate to find them, just to reframe them. >

Applying in your example, it would be enough to iterate the array json.games check if elemento.stats.win == true and save the values you want. If we did everything would look like this:

var tipoJogo = [];

json.games.forEach(function(jogo){
  // Verificando se o jogo.win é verdadeiro
  // Quando se quer apenas saber se o valor é verdadeiro,
  // não é necessário compará-lo à true, apenas referenciá-lo
  // (jogo.stats.win) ao invés de (jogo.stats.win == true)
  if (jogo.stats.win) {
    console.log('Jogo ganho', jogo.stats.win);
  }

  // Guardando o gameType em outra variável
  // O método push() serve pra adicionar valores no final de uma array
  tipoJogo.push(jogo.gameType);
});
    
28.05.2016 / 20:50