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

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).