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

experimented with a table for this challenge

For this Build an Object Challenge I thought it'd be cool to try it out displaying the information in a table.

function print(message) {
  var outputDiv = document.getElementById('output');
  outputDiv.innerHTML = message;
}

var html = '';
//create the header
html += '<table><tr>';
for ( var key in students[0] ) {
  html += '<th>' + key + '</th>';
}
html += '</tr>';
//fill out the values
for ( var i = 0; i < students.length; i++) {
  html += '<tr>';
  for ( var stuff in students[i]) {
    html += '<td>' + students[i][stuff] + '</td>';
  }
  html += '</tr>';
}
html += '</table>';

print(html);

I tested it out and am pretty sure it is scalable for adding/removing students or adding more keys to the objects for extra information. Thought it would be worth trying to do it this way. Lemme know if anything could be improved on this.

Thanks guys!

-Wolfgang

1 Answer

I think the only issue you might have is that the order of keys isn't guaranteed with a for...in loop. So because you're looping over them multiple times, you might get the 'headers' or keys in a different order than the values.

One way around that would be to combine the two loops, and use a counter that you increment at the end of each iteration, and only print the headers during the first iteration (i.e. the counter is still the initial value that you set it to).