skip to Main Content

I am working on javascript to iterate over an object. Which contain a nested objects. The nested objects contain another objects.

How to iterate over all keys and values of entire object?

I have an object inside nested objects. every nested contains with some keys and values i have written for loop to iterate over object keys, I got the result what i expected, But nested object iterated twice : Temporary Address :[object Object], which i don’t want to display.

The code I have written I got the expected result, But nested object coming twice. I tried to stop it with different dot notations and all but it’s not working.

// javaScript code 
const MainObj = {
  name: "Peter",
  age: 30,
  address: {
    Country: "America",
    TemporaryAddress: {
      state: 'New York',
      pincode: "10009"
    },
    PermanentAddress: {
      state: 'Texas',
      pincode: "75243"
    }
  }
}
for (let key in MainObj) {
  if (MainObj[key] instanceof Object) {
    let innerObj = MainObj[key];
    for (let item in innerObj) {
      console.log(item + " :" + innerObj[item])
      let addr = innerObj[item]
      if (innerObj[item] instanceof Object) {
        for (k in innerObj[item]) {
          console.log(k + " :" + addr[k])
        }
      }
    }
  } else {
    console.log(key + " : " + MainObj[key])

  }
}

2

Answers


  1. The problem is that you are printing in the second nesting level regardless of whether the data is an object or not, causing some undesirable parts to print. You can fix that by moving your prints to an else block, but there is a better way to do the nested traversal of an object, using recursive functions. The code below defines printObject, which prints all of the non-Object key-value pairs for an object with arbitrarily deep nesting by calling itself on any entries that are Objects

    const MainObj = {
      name: "Peter",
      age: 30,
      address: {
        Country: "America",
        TemporaryAddress: {
          state: 'New York',
          pincode: "10009"
        },
        PermanentAddress: {
          state: 'Texas',
          pincode: "75243"
        }
      }
    }
    
    function printObject(obj) {
      for (let key in obj) {
        let innerObj = obj[key]
        if (innerObj instanceof Object) {
          printObject(innerObj)
        } else {
          console.log(key + ":", innerObj)
        }
      }
    }
    
    printObject(MainObj)

    If you want to avoid recursion, all you need to do is put your printing in the else block after the instanceof Object check, so that it doesn’t print items that are Objects

    const MainObj = {
      name: "Peter",
      age: 30,
      address: {
        Country: "America",
        TemporaryAddress: {
          state: 'New York',
          pincode: "10009"
        },
        PermanentAddress: {
          state: 'Texas',
          pincode: "75243"
        }
      }
    }
    for (let key in MainObj) {
      if (MainObj[key] instanceof Object) {
        let innerObj = MainObj[key];
        for (let item in innerObj) {
          let addr = innerObj[item]
          if (innerObj[item] instanceof Object) {
            for (k in innerObj[item]) {
              console.log(k + " :" + addr[k])
            }
          } else {
            console.log(item + " :" + innerObj[item])
          }
        }
      } else {
        console.log(key + " : " + MainObj[key])
    
      }
    }
    Login or Signup to reply.
  2. You could take a recursive approach and return an array of keys and value.

    const
        getEntries = object => Object
            .entries(object)
            .flatMap(([k, v]) => v && typeof v === 'object'
                ? getEntries(v).map(a => [k, ...a])
                : [[k, v]]
            ),
        data = { name: "Peter", age: 30, address: { Country: "America", TemporaryAddress: { state: 'New York', pincode: "10009" }, PermanentAddress: { state: 'Texas', pincode: "75243" } } };
        
    console.log(getEntries(data));
    .as-console-wrapper { max-height: 100% !important; top: 0; }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search