0

I am using Nodejs with ejs template. I have an array in my Nodejs backend that looks like this:

array= [false,false,false,false]

Now, if I try to send this to my ejs doing something like

res.render("home",{myarray:array}

and in my ejs(frontend)

let myarray = <%- myarray %>

I get:

Uncaught SyntaxError: Unexpected token false

which upon inspection shows

let myarray = false,false,false,false

However, in my backend if I change

res.render("home",{myarray:array}

to

res.render("home",{myarray:JSON.stringify(array)}

Everything works fine. Myarray now becomes an array again:

[false,false,false,false]

I just do not understand why JSON.stringify helps me send an array from the backend to the front end when I cannot send a regular array.

jedu
  • 1,211
  • 2
  • 25
  • 57
  • duplicated question at https://stackoverflow.com/questions/38179668/passing-an-array-from-ejs-to-javascript – Chris Chen Sep 21 '19 at 06:12

2 Answers2

1

You can use direct array in your ejs but you will have to use the loop in ejs. If you are sending via JSON.stringify you can revert via JSON.parse();

Ankit Kumar Rajpoot
  • 5,188
  • 2
  • 38
  • 32
0

In general, when frontend read anything from the server everything is in document/string format and needs to be deciphered.

Since ejs will pass variables in html format, all variables will need to be stringified.

Instead of passing the stringified variable directly, You can stringify your variables in Scriptlet as well. let myarray = <%- JSON.stringify(myarray) %>

Chris Chen
  • 1,228
  • 9
  • 14