0

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

2 Answers 2

9

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
Sign up to request clarification or add additional context in comments.

2 Comments

Also make sure you do html = '' at the beginning.
@u_mulder, Thank you kind sir. I do hate it when the solution stares me in the face. Hva a nice day!
2

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">';

1 Comment

thank you. It never occurred to me that i was replacing the value of my variable. Such a simple mistake, but so easy to fix. Have a nice day.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.