Home > Net >  Iterate nested object with for loop
Iterate nested object with for loop

Time:12-05

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.

CodePudding user response:

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)
}
  • Related