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

Script only writes a single object to page... not 5

For some reason this only gives me the last object in the array. What am I missing??? Thanks in advance!

let arrayItem;
let result = '';

let students = [
  {
    name: "Mike", 
    track: "IOS", 
    achievements: 5, 
    points: 345
  },
  {
    name: "Steve", 
    track: "JS", 
    achievements: 6, 
    points: 234
  },
  {
    name: "Jay", 
    Ttack: "IOS", 
    achievements: 8, 
    points: 989
  },
  {
    name: "Sally", 
    track: "Python", 
    achievements: 2, 
    points: 123
  },
  {
    name: "Tom", 
    track: "JSON", 
    achievements: 9, 
    points: 3415
  }
];

for (let i = 0; i < students.length; i++) {
  arrayItem = students[i];                   
  result = arrayItem.name + '<br>';          
  result += arrayItem.track + '<br>';         
  result += arrayItem.achievements  + '<br>';
  result += arrayItem.points + '<br>';
}

document.write(result);

2 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there, francisobrien ! You're doing great. The problem here is that every time you start a new iteration of that loop, you are taking result and starting it over again from scratch. You should be concatenating on to it through every iteration.

This line:

 result = arrayItem.name + '<br>';  

Should contain concatenation as well like so:

 result += arrayItem.name + '<br>';  

If it's just the equal sign, it's only an assignment operator and everything that was there gets wiped out entirely. That means that the one thing that will show will be whatever was in the last iteration of that loop.

Hope this helps! :sparkles:

Got it. Thanks Jennifer!