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 Loops, Arrays and Objects Tracking Data Using Objects The Build an Object Challenge, Part 2 Solution

Elvin Tsang
Elvin Tsang
4,764 Points

Dynamically retrieve the properties and property values

In the answer given, each of the remaining 3 properties for each person are specified in the code. What if you wanted to loop through and return each property with its related value without 'knowing' the property name for each? i.e. the code would be dynamic and adapt to the object contents should they change - the below was my attempt:

var message = "<p>";

for ( i = 0; i < students.length; i += 1 ) {
  message += "<h2> Student: " + students[i].name + "</h2>";
  for ( var prop in students[i] ) {
    message += "<p> " + prop + ": " + students[i][prop] + "</p>";
  }
}

message += "</p>"

document.write(message);

Is this not a better way to approach the problem (I assumed this was what the exercise was asking first time around) The problem with the above is that the loop returns all 4 properties (we want to exclude the first one) and also there is an issue with capitalisation.

Does anyone have a solution to the above?

Thanks

Clara Roldan
Clara Roldan
3,074 Points

I took the same approach, I guess you could handle capitalisation with CSS and maybe add an if() statement to look for the 'name' property and change it to "student". It looks a bit dirty though, maybe someone has a better solution?

1 Answer

rdaniels
rdaniels
27,258 Points

in your second "for" loop should it be: students[i]. prop (no brackets), like the above "for" loop has students[i].name ?