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:

const dataToSend = [
  {
    id: "ID",
    name: "Name"
  },
  {
    id: "ID",
    name: "Name"
  }
]

res.render('configure', {
    array: dataToSend
});

And getting it on the frontend with ejs this way:

<%= array %>

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:

Tags
<% 'Scriptlet' tag, for control-flow, no output
<%_ ‘Whitespace Slurping’ Scriptlet tag, strips all whitespace before it
<%= Outputs the value into the template (HTML escaped)
<%- Outputs the unescaped value into the template
<%# Comment tag, no execution, no output
<%% Outputs a literal '<%'
%> Plain ending tag
-%> Trim-mode ('newline slurp') tag, trims following newline
_%> ‘Whitespace Slurping’ ending tag, removes all whitespace after it

source: https://ejs.co/

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

<%- JSON.stringify(array) %>
Advertisement