1

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]]

1 Answer 1

4

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>
Sign up to request clarification or add additional context in comments.

1 Comment

This works perfectly fine, thanks! But can i ask why and when does that happen?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.