I'm trying to make a journal but can't get it to work. I'm trying to make a for loop that posts the posts that I compose, in an array on the home page. I get connection between the app file and the ejs file because the inputs shows up when I log it in the terminal. I just can't get it to show up on the home page. I just want the title of the input to show up, but I keep getting [object Object],[object Object],[object Object] and I can't understand why?
<h1>Home</h1>
<P> <%= startingContent %> </P>
<%- console.log(posts);-%>
<ul>
<% posts.forEach(function(post, i) { %>
<li>Posts <%= posts %></li>
<% }); %>
</ul>
const posts = [];
app.get("/", (req, res) => {
res.render("home",{ startingContent: homeStartingContent , posts:posts});
posts: [
{posts: posts},
{posts: posts}
]
//console.log(posts);
});
CodePudding user response:
I guess you are trying to output an Object as a string.
In order to print an object out you first need to parse it using JSON.parse(myObject), then you can print it out and it's gonna be readable instead of just [object Object].
If you wanna just access a property you can use myObject.myProperty or myObject["myProperty"]
CodePudding user response:
let x ={
first:1,
second:{
third:3,
fourth:[{
fifth:4
}],
sixth:{
seventh:5
}
},
eighth:[1,2],
ninth:[{
tenth:10
}]
}
console.log(x) // { first: 1, second: { third: 3, fourth: [ [Object] ],sixth: { seventh: 5 } }, eighth: [ 1, 2 ],ninth: [ { tenth: 10 } ] }
parsing in javascript works only till 2 level. it converts array of objects to [object, object].
let x ={
first:1,
second:{
third:3,
fourth:[{
fifth:4
}],
sixth:{
seventh:5
}
},
eighth:[1,2],
ninth:[{
tenth:10
}]
}
console.log(JSON.stringify(x)) // {"first":1,"second":{"third":3,"fourth":[{"fifth":4}],"fi":[7],"sixth":{"seventh":5}},"eighth":[1,2],"ninth":[{"tenth":10}]}
try using JSON.stringify() to get the whole object
CodePudding user response:
[object Object] is a string version of an object instance. This value is returned by a JavaScript program if you try to print out an object without first formatting the object as a string.
This is the syntax for the [object Object] object: [object Object] JavaScript Example Take this example:
let objA = {
name: "christina",
degree: "music",
instrument: "flute"
}
