0

I am trying to create an unordered list of food items that show once I click a button. I am trying to display the name of each item only. However instead of showing the item names, I am getting an unordered list with each item displaying [object Object].

image of four bullet points stating object Object

How can I display the list item names in my list instead of [object Object]?

let groceryList = [
{name: "banana", price: 5},
{name: "milk", price: 3},
{name: "bread", price: 1},
{name: "chips", price: 2}
]

let ul = document.getElementById("itemList")
let btn = document.getElementById("btn")

btn.addEventListener("click", function () {
     for (let i = 0; i < groceryList.length; i++) {
         let item = groceryList[i]
         let li = document.createElement("li")
         li.appendChild(document.createTextNode(item))
         ul.appendChild(li)
     }
        
 })
2
  • because you are stroing an object into a string and it runs toString(). You need to reference the properties of the object to get the text .createTextNode(item.name) Commented Aug 19, 2022 at 15:22
  • 1
    The object is managed in memory, so its native representation is [object Object]. You may want to stringify it: li.appendChild(document.createTextNode(JSON.stringify(item))) Commented Aug 19, 2022 at 15:23

2 Answers 2

2

Where you say:

let item = groceryList[i]

That returns an object and thus displays as [object Object]. You can access the properties of this object with groceryList[i].name and groceryList[i].price; that will return a string or number respectively.

Sign up to request clarification or add additional context in comments.

Comments

0

let item = groceryList[i] return whole object, if you want to access the value of name or price, you should access it by using key of that value.

let groceryList = [
{name: "banana", price: 5},
{name: "milk", price: 3},
{name: "bread", price: 1},
{name: "chips", price: 2}
]


 
 groceryList.forEach(item => {
  console.log("item", item)
  //To access the name
  console.log("name", item.name)
  //To access the price
  console.log("price", item.price)
 })

Comments

Your Answer

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