Skip to content
Advertisement

The frontend receives an array as [object Object]

I am building a website with JavaScript, express.js, ejs and Node.js and i just ran into a problem.

I am sending an array to the frontend this way:

JavaScript

And getting it on the frontend with ejs this way:

JavaScript

If i print the array on the frontend the result will be [object Object] and I also printed out typeof('<%= array %>') which returned string.

I found some topics about this but i coun’t find anything that helps. I would like to know what is the proper way to do this. Thanks.

Advertisement

Answer

The problem here is that the array is being converted to a string. In JavaScript, objects ({...}) have a toString method that returns the string [object Object] by default.

To solve this, you need to ensure that the array isn’t being converted to a string.

In EJS, you have a variety of tags to choose from:

JavaScript

source: https://ejs.co/

You’re likely looking for this: <%- to output the JSON.stringify‘d array.

JavaScript
Advertisement