Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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]?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading