[SOLVED] How do I list Javascript array of objects in HTML – Stack Overflow

Issue

This Content is from Stack Overflow. Question asked by Tom

I have an array of objects like this:

const people = [
    { name: 'Bill', dob: '1949-08-11' },
    { name: 'Jill', dob: '1949-08-18' }
]

I’d like to list them inside my html document, inside a wrapper div.

This is what I tried.
I’m using a for loop like this:

for (let i = 0; i < people.length; i++) {
    wrapper.innerHTML = people[i].name   
}

But this only outputs one name.

The same happens when I try it with forEach

people.forEach( person => {
    console.log(person.name)
   wrapper.innerHTML = person.name
})

The console.log lists both names, but in the html only one item is listed.

What am I doing wrong?



Solution

You can use a variable to store it

var content = "";
for (let i = 0; i < people.length; i++) {
    content += people[i].name + " ";   
}
wrapper.innerHTML = content;

Another choice is to create element dynamiclly

const people = [
    { name: 'Bill', dob: '1949-08-11' },
    { name: 'Jill', dob: '1949-08-18' }
];

var ul = document.querySelector("#user_list");
people.forEach(p =>{
  var li = document.createElement("li");
  li.innerHTML = "name: " +p.name +"    dob: " + p.dob;
  ul.append(li);
});
<div>
  User infos:
  <ul id="user_list">
  </ul>
</div>


This Question was asked in StackOverflow by Tom and Answered by lucumt It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?