Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

113
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda