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!

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 Objects Loop Through Objects Display an Array of Objects on the Page – One Solution

The Output displays info of only one pet. I have checked my code several times but I can't seem to find any error.

Here's My code

const pets = [
    name: 'Joey',
    type: 'Dog',
    breed: 'Australian Shepherd',
    age: 8,
    photo: 'img/aussie.jpg'
    name: 'Patches',
    type: 'Cat',
    breed: 'Domestic Shorthair',
    age: 1,
    photo: 'img/tabby.jpg'
    name: 'Pugsley',
    type: 'Dog',
    breed: 'Pug',
    age: 6,
    photo: 'img/pug.jpg'
    name: 'Simba',
    type: 'Cat',
    breed: 'Persian',
    age: 5,
    photo: 'img/persian.jpg'
    name: 'Comet',
    type: 'Dog',
    breed: 'Golden Retriever',
    age: 3,
    photo: 'img/golden.jpg'

let html = '';

for (let i = 0; i < Object.keys(pets).length; i++) {
  html = `
    <h3>${pets[i].type} | ${pets[i].breed}</h3>
    <img src="${pets[i].photo}" alt="${pets[i].breed}">

document.querySelector('main').insertAdjacentHTML('beforeend', html) ;

1 Answer

Steven Parker
Steven Parker
228,038 Points

The assignment operator (=) replaces the contents of HTML each time in the loop, so when the loop is done it will contain only the values from the last pass. You may have intended to use the concatenating assigment (+=) instead.

Also, you probably don't want to control the loop with the count of the keys; you likely meant to count the objects themselves (pets.length).