Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

Md Alauddin
Md Alauddin
1,977 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
217,573 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
217,573 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,977 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.