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).
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