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.
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"},...];