Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

293
Views
Defining and using an object passed from Express to EJS

In my route handler I pass an object (the object is the result of a SELECT query to database) to my ejs file that is rendered as follows:

const query = await pool.query('SELECT * FROM table');
const obj = query.rows();
response.render('/ejspage', {
   obj: obj
});

In my ejs file I am then trying to assign this object to a variable and loop through it:

<script>
   var data = '<%= obj %>';

   data.forEach(function(o) {
      console.log(o);
   }
</script>

This causes the following error: Uncaught TypeError: obj.forEach is not a function

I have tried using JSON.parse(obj) but this results in the following error Uncaught SyntaxError: Unexpected token o in JSON at position 1

I've also tried JSON.stringify(obj) to resolve the error with no luck

When I print out the variable console.log(obj) I get:

[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

I know that I can use embedded javascript in ejs (when I do this I can use forEach() on obj just fine) but for my specific purpose I would like to do it the way shown (i.e. within the <script> tags).

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

you need to use both JSON.stringify and JSON.parse

 <script>
   var data = JSON.parse('<%= JSON.stringify(obj) %>');

   data.forEach(function(o) {
      console.log(o);
   }
</script>

i found that in some cases that JSON parse of JSON stringify still gave error and took inspiration from a post doing cookie parse

 <script>
   var data = JSON.parse(decodeURIComponent('<%=encodeURIComponent( JSON.stringify(data) ) %>')) 

   data.forEach(function(o) {
      console.log(o);
   }
</script>

a alternative is using res.cookie but it is limited to 4 MB

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!