简体   繁体   中英

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM