Loop nested object using for..in loop
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:
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:
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.