Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

298
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda