Ejs variables in script tag/ setting array to variable become string

Issue

So i needed to pass a variable to the script tag in the ejs file. it’s question array (i called it object in the var name for no reason), that i need to work with in the script tag. i saw that it’s done by '<%-varname%>' .
But the thing is, i want to remove stuff from the array while working with it, so i need a copy of this array. And here is the problem:

console.log('<%-passedUser.questionsObject%>')
console.log('<%-passedUser.questionsObject[0]%>')
arrayToUse = '<%-passedUser.questionsObject%>'
console.log(arrayToUse)
console.log(arrayToUse[0])

Output:

question1,answer1,answer2,answer3,answer4,answer5,q2,answer1,answer2 

question1,answer1,answer2,answer3,answer4,answer5 

question1,answer1,answer2,answer3,answer4,answer5,q2,answer1,answer2 

q

I tried JSON.stringify, parse, nothing works. i’d appreciate any help.

Note: i don’t know why '<%-passedUser.questionsObject%>' isn’t logging the correct way, but it’s giving correct values. It’s true form is :

[[question1,answer1,answer2,answer3,answer4,answer5],[q2,answer1,answer2]]

Solution

you have to use both json parse and json stringify

arrayToUse = JSON.parse('<%- JSON.stringify(passedUser.questionsObject)%>')

later you can easily split the array using

const [questions,answers] = arrayToUse

or do it before sending it to the client

<% const [questions,answers] = passedUser.questionsObject %>

<script>
  const  arrayToUse = JSON.parse('<%- JSON.stringify(questions)%>')
</script>

Answered By – Divine Soul

Answer Checked By – Dawn Plyler (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.