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

Why can't you just loop through and print both the key and value at the same time?

It seems like logically you should be able to just loop through both the object key and value (using dot notation) at the same time instead of having to write out the "student.property" statements. Something like:

for (var i = 0; i <= students.length; i +=1) { var student = students[i]; for (var prop in student) { document.write("<p>", prop, ": ", prop.prop, "</p>"); } };

2 Answers

Steven Parker
Steven Parker
177,686 Points

You can't use dot notation there because "prop" is not the name of the property, it's a variable that contains the name.

But you can still do it, just using bracket notation instead:

    document.write("<p>", prop, ": ", student[prop], "</p>");

Thanks Steven! I finally figured that out through trial and error and wound up with just what you wrote:

for (var i = 0, l = students.length; i < l; i++) {
    var student = students[i];
        for (var prop in student) {
           var value = student[prop];
                document.write("<p>" + prop + " : " +  value  + "</p>");
    }
}