Frederick M. Rogers
Frederick M. Rogers

Reputation: 921

Javascript - Looping over an array of objects, only last object show

i spent a bit trying to make title that explained the issued but i fear it fell a bit short of the issue i am having.

in short, i am using a for loop to iterate over this array of objects.

var people = [
  {
      name: "John Doe",
      age: 33,
      gender: "male",
      loc: "Springfield"
   },
   {
      name: "Jane Doe",
      age: 32,
      gender: "female",
      loc: "Springfield"
   }
];

The for loop is run through a function passing two arguments, an element id and the array, like this.

var list = {
  html: function (el, array) {
    var container = document.getElementById(el), html;    
    for( var i=0;i<array.length;i++ ) {
      html  = '<div class="item">';
      html +=   '<h1>'+array[i].name+'</h1>';
      html +=   '<p>Age: '+array[i].age+'</p>';
      html +=   '<p>Sex: '+array[i].gender+'</p>';
      html +=   '<p>Location: '+array[i].loc+'</p>';
      html += '</div>';     
      console.log( array[i].name+', '+array[i].age+', '+array[i].gender+', '+array[i].loc );  
    } 
    container.innerHTML = html; 
  } 
}
list.html('list', people); 

The problem: The loop returns only the last object in the array. I am unsure why this is happening or how to solve it. Any assistance would be much appreciated. Thank you.

Here is a link to a: relevant demo

Upvotes: 0

Views: 1302

Answers (2)

ismaro3
ismaro3

Reputation: 79

The first instruction inside the foor loop is an assignment

html  = '<div class="item">'

so on every iteration the whole content of "html" gets replaced. You should use

html += '<div class="item">';

Upvotes: 2

u_mulder
u_mulder

Reputation: 54831

Init html var with empty string and add + in the beginning of for loop:

var container = document.getElementById(el), html = "";   
for( var i=0;i<array.length;i++ ) {
    html  += '<div class="item">';  // add plus here

Upvotes: 9

Related Questions