How do I list Javascript array of objects in HTML

Viewed 42

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?

2 Answers

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>

You are replacing the content of innerHTML on every call. you need to append the contents, something like

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

this should work.

Related