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

Eric Jusic
Eric Jusic
4,350 Points

I used for in loop inside for loop, it's working. Is that good practice and if not, why?

Here is the code

var students = [

  {
    Name: 'John',
    Track: 'JavaScript',
    Achievements: 3,
    Points: 343,
  },
  {
    Name: 'Mathew',
    Track: 'Java',
    Achievements: 6,
    Points: 654,
  },
  {
    Name: 'Jane',
    Track: 'PHP',
    Achievements: 11,
    Points: 998,
  },
  {
    Name: 'Adam',
    Track: 'TypeScript',
    Achievements: 34,
    Points: 2718,
  },
  {
    Name: 'Joshua',
    Track: 'C++',
    Achievements: 38,
    Points: 3433,
  },

];


  function print(html){

  var get_elem = document.getElementById('output');
  get_elem.innerHTML = html;

  }
  var mainhtml = " ";

  for(var i = 0; i < students.length; i += 1){
   for(var props in students[i]){
     if(props === "Name"){

     mainhtml += '<h2>' + props + ": " + students[i][props] + "</h2><br> ";

     }else {

       mainhtml += '<p>' + props + ": " + students[i][props] + " </p><br> ";
     }

  }
}

  print(mainhtml);

2 Answers

Steven Parker
Steven Parker
229,771 Points

This is exactly the kind of situation where nested loops are a good choice. Each loop has a clear purpose: one interates through the array, the other iterates through the object properties.

Good job. :+1:

Eric Jusic
Eric Jusic
4,350 Points

Thanks Steven for review and confirmation, I appreciate that, means a lot. :)

A little late to the party, but I just completed this challenge without referencing anything and what you have here is pretty close to what I have. It's good to know another way, as referenced by the video, but I'm glad I'm not the only one who did this.