Traversing complex JSON structure with java Script

Asked

Viewed 763 times

0

Hello,

I’m starting now in the world of javascript, I would need help to traverse the following json structure: inserir a descrição da imagem aqui

I need for example to increment a counter when the field "win" is true, I need to store in variables the value contained in certain fields such as the field "gameType".

My Json(incorrect) is 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]);
            }
        }    
    }

Grateful from now on.

1 answer

1


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

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

To specification of forEach() abridged:

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 have passed the properties as well, as the properties always have a fixed name (for example the json.games[0].stats.win) you don’t have to iterate to find them, just re-do them.

Applying in your example would simply iterate the array json.games verify whether elemento.stats.win == true and save the values you want. If we do 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);
});
  • It worked out, thank you so much for the answer and for her explanation, amazing how I had complicated my code so much.

Browser other questions tagged

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