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);
}}
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 thatfindIndex
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"), therefindIndex
is an option.– hkotsubo
And about JSON not being the same as a Javascript object, read here: https://answall.com/a/517767/112052
– hkotsubo
@hkotsubo information of great value, I am immensely grateful for everything.
– Gorillaz