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
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 definesprintObject
, which prints all of the non-Object key-value pairs for an object with arbitrarily deep nesting by calling itself on any entries that areObject
sIf you want to avoid recursion, all you need to do is put your printing in the
else
block after theinstanceof Object
check, so that it doesn’t print items that areObject
sYou could take a recursive approach and return an array of keys and value.