'Array give [object object] after pushing object inside
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)
Solution 1:[1]
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>';
} `
}
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Exortions |
| Solution 2 | Dani3le_ |
