Is there a more efficient method of traversing a JSON and returning its index than FOR?

Asked

Viewed 51 times

1

I try to know if there is an optimized method, or at least more idiomatic, to go through this JSON and return its index, in case the player sought

const data = {
  "clubes": {
      "20" : {
         "id" : 20,
          "nome": "Grêmio",
          "estadio": "Arena Grêmio",
          "capacidade": 60.540,
          "escudo" : "url" }
    },
  "Jogadores": [{
      "jogador": {
          "nome": "Borja",
          "nacionalidade": "Colômbia",
          "posicao": "Atacante",
          "n_camisa": "9",
          "foto": "url",
          "clube_id": 20
  }},
  {
      "jogador": {

          "nome": "Brenno",
          "nacionalidade": "Brasil",
          "posicao": "Goleiro",
          "n_camisa": "1",
          "foto": "url",
          "clube_id": 20
        },
}]}
  
let buscar = "Brenno";
let indice;

for (let i = 0; i < data['Jogadores'].length; i++){

if (data['Jogadores'][i]['jogador']['nome'] == buscar) {
      indice = i; 
     console.log(indice); 
}}










 

  • 2

    If you are looking for a more efficient way, keep your code even, because use findIndex, as suggested below, it is slower: https://jsbench.me/dbks2gok5r/1 - remember that findIndex returns the index of the first element that satisfies the condition, while its loop searches all (if there is more than one). However, in the link I indicated, I changed the loop to return only the first one (and thus have a more "fair" comparison). Now if you want shorter code (which is not necessarily "better"), there findIndex is an option.

  • 1

    And about JSON not being the same as a Javascript object, read here: https://answall.com/a/517767/112052

  • 1

    @hkotsubo information of great value, I am immensely grateful for everything.

1 answer

4

The variable data is not JSON, it is a Javascript object. And in reality, its problem is to locate a specific object in an array of objects. For that there is the function findIndex(). You could try something like:

let buscar = "Brenno"; 
let indice = data.Jogadores.findIndex(e => e.jogador.nome === buscar);
console.log(indice);
  • This is exactly what I was looking for. And I apologize for my lack of knowledge, I thought it was a JSON. Thank you very much!

Browser other questions tagged

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