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

158
Vistas
Iterate nested object with for loop

how can I get the values of a nested object in a loop? I need to iterate through both levels:

for (let unit in ds1.units) {      
    for (let ports in ds1.units[unit].switchPorts) {
        console.log(ports)
    }
}

}

Object looks like this: Screen There is no output. When I access the value with ds1.units[unit].switchPorts I get it. Also I get the unit after the first for loop.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can't iterate Object by default.
Hence, there are multiple ways, but I prefer to convert the key to array. So the code would be:

for (let unit of Object.keys(ds1.units)) {      
    console.log(ds1.units[unit].switchPorts)
}

Also we're going to use of instead of in because of going to retrieve the value instead of index.

For test case:


ds1 = {
   units: {
      1: {
          switchPorts: 5,
        },
      2: {
          switchPorts: 6,
      }
   }
}


for (let unit of Object.keys(ds1.units)) {      
    console.log(ds1.units[unit].switchPorts)
}
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