Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Objects Loop Through Objects Use `for in` to Loop Through an Object's Properties

Md Alauddin
Md Alauddin
1,991 Points

Access the nested object using for in loop.

How do I display the object inside the object? I tried but need to use two loops for accessing the inner object. My solution -

const preEl = document.querySelector('#pre-el');

let family = {
    fatherName: 'Father Name',
    motherName: 'Mother Name',
    children: {
        kid1: 'Kid1 Name',
        kid2: 'Kid2 Name'
    }
};

for (const props in family) {
    console.log(`${props}:  ${family[props]}`);
    preEl.innerHTML += `${props}: ${family[props]}<br>`;
}
for (const objs in family.children) {
    console.log(objs + family.children[objs]);
    preEl.innerHTML += `  ${objs}: ${family.children[objs]}<br>`;
}

Result -

fatherName: Father Name
motherName: Mother Name
children: [object Object]
  kid1: Kid1 Name
  kid2: Kid2 Name

2 Answers

Steven Parker
Steven Parker
231,248 Points

This seems to be working as is, but you might want to add a test in the first loop so when the property is "children", print only the property name.

You could also nest the 2nd loop inside the first so that the kid's names will always follow the "children" property name, no matter what order it is encountered in while looping through the outer object.

Steven Parker
Steven Parker
231,248 Points

In your 2nd example, you've got the nesting set up — so now just use the conditional to control how the children property itself is displayed:

for (const props in family) {
    if (props === 'children') {
        preEl.innerHTML += `${props}:<br>`;  // display children this way
        for (const child in family.children) {
            preEl.innerHTML += `&ensp; ${child}: ${family.children[child]}<br>`
        }
    } 
    else {
        // and use this way for everything else
        preEl.innerHTML += `${props}: ${family[props]}<br>`;
    } 
}
Md Alauddin
Md Alauddin
1,991 Points
for (const props in family) {
    preEl.innerHTML += `${props}: ${family[props]}<br>`;
    if (props === 'children') {
        for (const child in family.children) {
            preEl.innerHTML += `${child}: ${family.children[child]}<br>`
        }
    }    
}

This is my second solution, but I can't delete the children's property.