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

Wojciech Samolowicz
Wojciech Samolowicz
7,532 Points

Can I use loop "for in" inside "for" loop in my solution ?

for ( i = 1; i < Students.length; i += 1 ) {
    document.write("<h2>Student:  " + Students[i].Name + "</h2>") ;
    for ( var prop in Students[i]) {
        document.write([prop] + ": " + Students[i][prop] + "<br>" );
    }
}

2 Answers

Steven Parker
Steven Parker
203,729 Points

You certainly can nest loops of the same or different types.

But you'll probably want to start the outer loop with "i = 0", since 0 is the index of the first item of an array. And you won't need any brackets around the word "prop" where it is used by itself.

Daniel Grigo
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Daniel Grigo
Full Stack JavaScript Techdegree Graduate 18,815 Points

In addition, if you write down the students name in the outer loop (which I also thought of first), it will be printed again during your inner loop under the "name" property. You could get around that with an if-clause:

 for (var i=0; i<students.length; i++){
   for (var prop in students[i]){
     if (prop=="name"){
      message+="<h2>Student: " +students[i][prop]+"</h2>";
    }
    else {message+="<br>"+prop+ ": "+ students[i][prop];
    }
  }
   message+="<p></p>";
 }