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

Kristaps Vecvagars
Kristaps Vecvagars
6,191 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;
};

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.