Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

294
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda