I am trying to pass an array to an .ejs page, however when I try use
var test ="<%= data %>";
console.log(test);
I get the output
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object
Console.log on the nodejs file works fine, but its when I try console.log client side it messes up.
As illustrated in the image above, the best way to navigate different web pages using ejs template is to ensure you create a folder called "partials" in your project's "views folder directory" where you have your other ejs files. 1) Then in that "partials folder" create 2 separate ejs files called header. ejs & footer.
The issue is likely with <%= data %>
, rather than console.log()
. If you check the result client-side, you'll probably see:
var test ="[object Object],[object Object],[object Object],...";
When you simply print an Array
, this will just .join()
the elements, calling .toString()
on each. And:
new Object().toString() === "[object Object]"
To output the data so it can be consumed, you can use JSON.stringify()
:
var test = <%- JSON.stringify(data) %>;
This takes advantage of JSON's syntax being based on JavaScript's synax to output an Array
literal of Object
literals:
var test = [{"prop":"value"},...];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With