Skip to content
the poor coder

Loop nested object using for..in loop

Poor Man
Published
Reading time
2 min read
On this page

Loop nested object using for..in loop#

Looping through a nested object can be tricky if you don't know how to handle it. Here's one method to loop through a nested object using a for..in loop.

Method 1: Using nested for..in loop#

One way to loop through a nested object is to use a nested for..in loop. Here's an example:

Text

  const obj = {
    name: 'John',
    age: 30,
    address: {
      street: '123 Main St',
      city: 'Anytown',
      state: 'CA',
      zip: '12345'
    }
  };
  
  for (let key in obj) {
    if (typeof obj[key] === 'object') {
      for (let nestedKey in obj[key]) {
        console.log(nestedKey + ': ' + obj[key][nestedKey]);
      }
    } else {
      console.log(key + ': ' + obj[key]);
    }
  }
  

In the above example, we have an object with a nested object called "address". We check if a key's value is an object by using the typeof operator. If it's an object, we loop through the nested object using another for..in loop. If not, we simply log the key and value to the console.

Method 2: Using recursion#

Another way to loop through a nested object is to use recursion. Here's an example:

Text

  const obj = {
    name: 'John',
    age: 30,
    address: {
      street: '123 Main St',
      city: 'Anytown',
      state: 'CA',
      zip: '12345'
    }
  };
  
  function loopObject(object) {
    for (let key in object) {
      if (typeof object[key] === 'object') {
        loopObject(object[key]);
      } else {
        console.log(key + ': ' + object[key]);
      }
    }
  }
  
  loopObject(obj);
  

In the above example, we define a function that takes an object as a parameter. We then loop through the object and check if a key's value is an object. If it's an object, we call the function recursively with that object as the parameter. If not, we simply log the key and value to the console.

These are just two ways to loop through a nested object using a for..in loop. There are other ways to achieve the same result, but these two methods should get you started.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC