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

Kristaps Vecvagars
Kristaps Vecvagars
6,193 Points

Would anyone care to give feedback on my solution?

It seemed natural to me to write 2 loops for this challenge. The first loop would run through the array that has the objects stored in it, and the 2nd loop would tun through each of the properties of every object. I also wrote the entire thing as a function, just in case. That way, if I'm thinking right, I wouldn't have to worry about the number of objects in the array AND the number of properties each object has.

Is this a reasonable approach?

// test_array is my array of objects
// test_list is the message string
// both of them are predefined, of course, i just didn't include the definitions here

function printStudents() {
  for (let i = 0; i < test_array.length; i++) {
    for (let key in test_array[i]) {
      test_list += key + ": " + test_array[i][key] + "<br>";
    }
  }
  document.getElementById("output").innerHTML = test_list;
};

1 Answer

I took JS elsewhere but this seems reasonable to me. For smaller jobs a double for loop seems lest costly to me too. You could also checkout the forEach() method that has you run a function for each element in an array.