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 trialMd Alauddin
1,991 PointsAccess 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
231,275 PointsThis 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.
Md Alauddin
1,991 Pointsfor (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.
Steven Parker
231,275 PointsSteven Parker
231,275 PointsIn 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: