Home > other >  Why do I get [object Object] instead of the object property value?
Why do I get [object Object] instead of the object property value?

Time:08-20

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)
     }
        
 })

CodePudding user response:

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.

CodePudding user response:

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)
 })

  • Related