JavaScript JavaScript Loops, Arrays and Objects Tracking Data Using Objects The Build an Object Challenge, Part 2 Solution

Md. Syful Islam
Md. Syful Islam
7,116 Points

The Treehouse solution is great but I tried to produce the output dynamically!

The solution given by Dave where he hardcoded the property names. But my attempt was for producing the result dynamically. My for loop was as following:

for (let i = 0; i < students.length; i++) {
  for (let key in students[i]) {
    let propName = key;
    let propValue = students[i][key];
    message += `<h2>${propName} : ${propValue} </h2>`;
  };
};

Though it produces the same result, it doesn't look exactly as Dave because of the HTML output.

Would appreciate if anyone review my code. Cheers!

1 Answer

Blake Larson
Blake Larson
12,700 Points

Yes that works! You can also clean it out a little more because you already have the key and specific student in each iteration of the for/in loop so you don't have to set the variables. Setting the propValue variable would be a good idea if you are using students[i][key] multiple times in the code block to make it cleaner but this is a one line block.

for (let i = 0; i < students.length; i++) {
  for (let key in students[i]) {
    message += `<h2>${key} : ${students[i][key]} </h2>`;
  };
};
Md. Syful Islam
Md. Syful Islam
7,116 Points

Yeah right! The code can be cleaner this way. Thanks for your reply. Appreciate it!