Home > Back-end >  Array give [object object] after pushing object inside
Array give [object object] after pushing object inside

Time:05-03

The array show as [object object] after I push the object inside it even though the object that are inside the array show up as what I want it to be . I tried searching google and YouTube but didn't find anything

let arr = []
let list = ""
let rev = {}
const btn = document.getElementById("savel")
btn.addEventListener("click", function() {
                 val1 = name.value
                 val2 = age.value
                shh ()                              
                console.log(val1)
})

function shh () {
     rev = {
                names: val1,
                ages: val2
}
showname.textContent = rev.names
showage.textContent = rev.ages
   arr.push(rev)
   console.log(arr)
   uul ()
}

function uul () {
                for (i=0; i<arr.length; i  ) {
                                list = arr[i]
                }
                ul.innerHTML  = `
                <li> ${list} </li>
                `
}
console.log(rev)

CodePudding user response:

You're appending to the list array after the for loop ends. Change the uul function to:

function uul () {
    for (i=0; i<arr.length; i  ) {
        list = arr[I];
        ul.innerHTML  = '<li> ${list} </li>';
    }           `
}

CodePudding user response:

You should use JSON.stringify().

If I have the following array and I try to show it in an alert

var myArray = [{name: "Jack"}, {name: "John"}];
alert(myArray);

The output will be [object Object],[object Object],

But if I use JSON.stringify:

alert(JSON.stringify(myArray))

the output will be [{"name":"Jack"},{"name":"John"}].

The same logic applies to your code and into the ul.innerHTML. Read more about here.

  • Related