Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

156
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!