Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

112
Visualizações
Obtain the same result with one or more keys in objects

With these objects

let myObjectA = {"fruits": {"item1":1, "item2":1}, "vegetables": {"item3":1, "item4":1} },
    myObjectB = {"fruits": {"item5":1, "item6":1} };

I need to do the same for loop for obtaining the keys, but when I do the same for loop

for(var i in myObjectA){
    print(myObjectA[i]);
  }
  for(var j in myObjectB){
    print(myObjectB[j]);
  }

In the first loop I get the two items, but in the second I get undefined

How do I get the fruits result, even when it is only one key in the object? I need a dynamic for loop because I don't know in advance if I'll get a one or two keyed objects

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

It's a typo as mentioned, but for reference, you can also obtain object keys with... wait for it... Object.keys :)

let myObjectA = {
    "fruits": {
      "item1": 1,
      "item2": 1
    },
    "vegetables": {
      "item3": 1,
      "item4": 1
    }
  },
  myObjectB = {
    "fruits": {
      "item5": 1,
      "item6": 1
    }
  };

let keys = Object.keys(myObjectA);
console.log(keys);

keys.forEach(k => {
  let item = myObjectA[k];
  let subkeys = Object.keys(item);
  console.log(`subkeys of ${k}`, subkeys)
})

about 4 years ago · Juan Pablo Isaza Relatório

0

You are passing i in myObjectB[i]

for(var i in myObjectA){
    print(myObjectA[i]);
  }
  for(var j in myObjectB){
    print(myObjectB[j]); // correction pass j not i
  }
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda