OrangeSoLlama
OrangeSoLlama

Reputation: 7

Display an array of objects on a page

I'm trying to render objects that are in an array into my DOM. I'm trying to display each object in its own card for viewing (using Tailwind css). I'm fairly new to coding so I feel like it's something very simple that I'm overlooking here. Any help would be greatly aprpeciated!

const productsDOM = document.querySelector(`.products`);

const itemObject = [{
    title: "Chocolate",
    price: 10.99,
    id: 1,
    img: "https://images.pexels.com/photos/1055272/pexels-photo-1055272.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260"
}, {
    title: "Whipped Cream",
    price: 12.99,
    id: 2,
    img: "https://images.pexels.com/photos/1055270/pexels-photo-1055270.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260"
}, {
    title: "White Frosting",
    price: 12.99,
    id: 3,
    img: "https://images.pexels.com/photos/1055271/pexels-photo-1055271.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260"
}, {
    title: "Berry",
    price: 14.99,
    id: 4,
    img: "https://images.pexels.com/photos/3081657/pexels-photo-3081657.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260"
}, {
    title: "Deluxe",
    price: 19.99,
    id: 5,
    img: "https://images.pexels.com/photos/1998634/pexels-photo-1998634.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260"
}, {
    title: "Oreo",
    price: 14.99,
    id: 6,
    img: "https://images.pexels.com/photos/783274/pexels-photo-783274.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260"
}];

function displayProducts() {
    let html = ``;
    itemObject.forEach(() => {
        html += `
        <div id="item-1" class="bg-white rounded-lg">
            <img class="rounded-md w-screen object-cover max-h-60"
                src="${itemObject.img}"
                alt="">
            <div class="py-2 px-8 text-gray-600">
                <div class="grid grid-cols-2 py-3 text-xl font-bold ">
                    <h3>${itemObject.title}</h3>
                    <p class="text-right">$${itemObject.price}</p>
                </div>
                <button data-id=${itemObject.id}
                    class="bg-purple-200 font-bold px-3 mt-2 text-xl py-4 w-full rounded-md transition-all hover:bg-purple-300">Purchase</button>
            </div>
        </div>
        `;
    });
    productsDOM.innerHTML = html;
}

Upvotes: 0

Views: 1861

Answers (3)

xhxe
xhxe

Reputation: 1487

You can use for loop, or even forEach() create Element, it doesn't matter it will be div, span, h1 or what and use innerText to declare your object names as text, and call your DOM Element before you use for loop and append them as child in your Element via .appendChild

In that case I used template strings it is easier to use, when you have to append lot of data from object

For Loop

const container = document.querySelector(".container")

const data = [
  {name: "george", age: 12},
  {name: "Maria", age: 35},
  {name: "Lucas", age: 65}
]

for(let i = 0; i < data.length; i++){
  const usersBox = document.createElement("div")
  usersBox.className = "usersBox"
  
  const list = document.createElement("p")
  
  list.innerText = `${data[i].name}: ${data[i].age}`
  usersBox.appendChild(list)
  
  container.appendChild(usersBox)
}
.usersBox{
  display: flex;
  border: 2px solid black
}
<div class="container">
</div>

.forEach()

const container = document.querySelector(".container")

const data = [
  {name: "george", age: 12},
  {name: "Maria", age: 35},
  {name: "Lucas", age: 65}
]

data.forEach(users => {
const usersBox = document.createElement("div")
  usersBox.className = "usersBox"
  
  const list = document.createElement("p")
  
  list.innerText = `${users.name}: ${users.age}`
  usersBox.appendChild(list)
  
  container.appendChild(usersBox)
})
.usersBox{
  display: flex;
  border: 2px solid black;
}
<div class="container">
</div>

Upvotes: 1

walidum
walidum

Reputation: 173

you have problem in your forEach loop, try this :

  function displayProducts() {
        let html = ``;
        itemObject.forEach((el) => {
            html += `
            <div id="item-1" class="bg-white rounded-lg">
                <img class="rounded-md w-screen object-cover max-h-60"
                    src="${el.img}"
                    alt="">
                <div class="py-2 px-8 text-gray-600">
                    <div class="grid grid-cols-2 py-3 text-xl font-bold ">
                        <h3>${el.title}</h3>
                        <p class="text-right">$${el.price}</p>
                    </div>
                    <button data-id=${itemObject.id}
                        class="bg-purple-200 font-bold px-3 mt-2 text-xl py-4 w-full rounded-md transition-all hover:bg-purple-300">Purchase</button>
                </div>
            </div>
            `;
        });
        productsDOM.innerHTML = html;
    }

Upvotes: 0

vanowm
vanowm

Reputation: 10201

You forgot to "capture" each element in your array inside forEach function:

    itemObject.forEach((item) => {

Once that's done, you can use item instead of itemObject inside your template. Also ID must be unique, so you can capture index of current item in the array as well and use it in your template:

    itemObject.forEach((item, index) => {

const productsDOM = document.querySelector(`.products`);

const itemObject = [{
    title: "Chocolate",
    price: 10.99,
    id: 1,
    img: "https://images.pexels.com/photos/1055272/pexels-photo-1055272.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260"
}, {
    title: "Whipped Cream",
    price: 12.99,
    id: 2,
    img: "https://images.pexels.com/photos/1055270/pexels-photo-1055270.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260"
}, {
    title: "White Frosting",
    price: 12.99,
    id: 3,
    img: "https://images.pexels.com/photos/1055271/pexels-photo-1055271.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260"
}, {
    title: "Berry",
    price: 14.99,
    id: 4,
    img: "https://images.pexels.com/photos/3081657/pexels-photo-3081657.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260"
}, {
    title: "Deluxe",
    price: 19.99,
    id: 5,
    img: "https://images.pexels.com/photos/1998634/pexels-photo-1998634.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260"
}, {
    title: "Oreo",
    price: 14.99,
    id: 6,
    img: "https://images.pexels.com/photos/783274/pexels-photo-783274.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260"
}];

function displayProducts() {
    let html = ``;
    itemObject.forEach((item,index) => {
        html += `
        <div id="item-${index}" class="bg-white rounded-lg">
            <img class="rounded-md w-screen object-cover max-h-60"
                src="${item.img}"
                alt="">
            <div class="py-2 px-8 text-gray-600">
                <div class="grid grid-cols-2 py-3 text-xl font-bold ">
                    <h3>${item.title}</h3>
                    <p class="text-right">$${item.price}</p>
                </div>
                <button data-id=${item.id}
                    class="bg-purple-200 font-bold px-3 mt-2 text-xl py-4 w-full rounded-md transition-all hover:bg-purple-300">Purchase</button>
            </div>
        </div>
        `;
    });
    productsDOM.innerHTML = html;
}

displayProducts();
<div class="products"></div>

Upvotes: 0

Related Questions