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

OZIO FRANCE
PLUS
OZIO FRANCE
Courses Plus Student 13,306 Points

Can someone please review my code for this challenge?

Here is my code:

code.js
// Assume you have the data objects here;

var name;
var track;
var achievements;
var points;
var html;

for(var i= 0; i < students.length; i++) {
  name = '<p><h1>' + students[i].name + '</h1></p>';
  track = '<p>' + students[i].track + '</p>';
  achievements = '<p>' + students[i].achievements + '</p>';
  points = '<p>' + students[i].points + '</p>';
  html = name + track + achievements + points;
  document.write(html);
}

I was wondering why on the solution, Dave is writing the key value instead of retrieve it from the object itself. I tried to do this but I cut my head off, and didn't found a solution to achieve my goal.

Is my code right? Is there any valuable reason why Dave is writing the key value hardcoded instead of retrieving it from the Object itself?

Thanks

[MOD: Edited to show formatted code]

Jake Lundberg
Jake Lundberg
13,965 Points

Do you mean 'Student: ', 'Track: ', etc...that he is typing out?

2 Answers

Ryan Boone
Ryan Boone
26,518 Points

I'm going to go out on a limb and assume students is an array of student objects, each of which contain several properties. It appears Dave is looping through each student object and systematically displaying each property in a block of HTML.

They key notation is being used to access each object in the order it appears in the students array. Then, each object's properties can be accessed. Does that make sense to you?

Jake Lundberg
Jake Lundberg
13,965 Points

Yes, it is possible to use javascript to get the names of the attributes of the object instead of hard coding them, but that is a little outside the scope of this particular lesson I think. If you are curious to see how you could do this, check out:

Object.getOwnPropertyNames()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames