The user interface is presented with an array labeled as [object Object]

Currently working on a website using JavaScript, express.js, ejs, and Node.js and encountered a puzzling issue.

The data is being sent to the frontend in the following manner:

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

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

To retrieve it on the frontend using ejs, this method is employed:

<%= array %>

If the array is printed on the frontend, it displays as [object Object]. Further investigation by printing out typeof('<%= array %>') indicates that it is of type string.

Although I have come across some related discussions, none seem to provide a solution to this dilemma. Seeking advice on how to handle this situation correctly. Thank you.

Answer №1

The issue at hand is that the array is being mistakenly transformed into a string. In JavaScript, objects ({...}) come with a toString function which typically presents the result as [object Object].

To tackle this problem, it's crucial to prevent the array from getting converted into a string.

When working with EJS, you have a diverse range of tags available:

Tags
<% 'Scriptlet' tag, for controlling flow without displaying output
<%_ ‘Whitespace Slurping’ Scriptlet tag, removes any preceding whitespace
<%= Inserts the value into the template (HTML escaped)
<%- Inserts the value unescaped into the template
<%# Comment tag, no execution or output
<%% Outputs a literal '<%'
%> Standard closing tag
-%> Trim-mode ('newline slurp') tag, trims following newline characters
_%> ‘Whitespace Slurping’ ending tag, eliminates all subsequent whitespace

source:

If you're searching for a solution, consider using: <%- to display the array after using JSON.stringify.

<%- JSON.stringify(array) %>

Answer №2

Have you tried assigning the array in a script? If so, it may be returning as a string. Here's a different approach to try: First, outside of the script tag, stringify the JSON data and assign it to a variable like this:-

<% let newArray = JSON.stringify(array) %>

Next, within the script tag, parse the EJS local variable newArray. Here is how you can do it:

<script>
let assignedArray = JSON.parse("<%- newArray %>");
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am curious about why I am unable to utilize inline functions in component props. Could you please provide a detailed explanation and perhaps give an example to illustrate? Furthermore, what is

Please take note: The component prop accepts a component, not a render function. Do not pass an inline function (e.g. component={() => }), as this will cause your component to unmount and remount, losing all state when the parent component re-renders. F ...

Unable to identify the C++ data type

Currently, I am developing a c++ program using Eclipse CDT and utilizing the gcc compiler on Ubuntu 13. The program consists of two classes named Function and Trial. Within the Trial class, there is a line of code where I am attempting to allocate an array ...

To ensure proper formatting, I must include a comma operator for numbers while typing and limit the decimal places to two

Could someone assist me in formatting a number to include commas and restrict the decimal places to two using regex? I have attempted the following, but need help making it work properly. Currently, when I enter a number it shows up as 1231244, however I ...

Jest - Silence greets the test results

Struggling with Jest has been a common theme for me ever since I first attempted to use it. Regardless of the tests I run or the options I try to pass to Jest, I never seem to get the expected 'Pass' or 'Fail' results in the console. In ...

Locating the index of the largest element in an array using Java

Struggling with a Java problem lately. I'm having trouble retrieving the array index that corresponds to the highest value. Oddly enough, I managed to find the index of the lowest value successfully. Here's my attempt: public static void main(S ...

What exactly is the purpose of editing a host file?

After reviewing this repository, an automatic message pops up: Don't forget to modify your host file 127.0.0.1 * http://localhost:3001 What exactly does that entail? ...

Stopping Popups in Chrome When Printing with JavaScript

Javascript function printPage(htmlPageContent) { var newWindow = window.open("about:blank"); newWindow.document.write(htmlPageContent); newWindow.print(); } In this code snippet, we are creating a new window 'newWindow' and then using ...

What is the best way to invoke functions in PHP based on their location in the code?

I am currently in the process of creating a sorting feature for some div elements using PHP. Initially, I have grouped each section into a separate function so that when I invoke this function, the section will be displayed. However, the issue I am facing ...

Saving the current date and time in PHP and JS to persist even after the browser has been closed

I am currently facing a situation where I can click on an image and it will display a new image. In the previous grid-item, it shows the day and time I clicked on it. What I want to achieve is to have this functionality persist even after closing and reop ...

Is it not possible to cast the incorrect type of the Typescript array.from(iterator)?

Encountering an error when converting flow code to typescript involving iterators. There seems to be a missing element in the iterator. const iter: Iterator<RouteData> = contentMap.routes(); const contentArray: Array<RouteData> = Array.from(it ...

Find the location where the function is declared

Can anyone help me locate the definition of this function: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#copyObject-property copyObject(params = {}, callback) ⇒ AWS.Request I'm struggling to find where it is defined. Any suggestio ...

Angularjs scope's parent id

I'm looking to access or manipulate a scope's grandparent without making things overly complicated. Leveraging the controller as syntax, I can reference the parent controller like so: this.applicationCtrl.something with applicationCtrl > paren ...

Transform an array with diverse keys in multiple dimensions into a CSV file with column headers

I am dealing with a multidimensional array of data structured as shown below: Array ( [0] => Array ( [CallID] => 793415338 [StartTime] => 2016-10-04 17:21:53 [CallingNo] => +15555555555 [queue1_time] => 9 ...

Substitute names and make copies in a bash associative array

My bash script is designed to determine if the input date ($1) falls within a specified date range. The user must provide a date as well as specify whether to check against range a or b ($2). #!/usr/bin/env bash today=$(date +"%Y%M%d") declare -A dict=$2 ...

What steps should I take to enable peer-to-peer payments within my application?

Can a payment gateway facilitate UserA to send direct payment to UserB after both parties have verified their credit card information? ...

How to use AngularJS to parse JSON containing backslashes

Here is the JSON data stored in $scope.projectData: [{ "\"Space\"": "\"L1 (1 floor)\"", "\"Subject\"": "\"Corridor Distance\"", "\"Label\"": "\"Corridor Distance\"", "\"Color&bso ...

Can you explain the distinction between $scope.$root and $rootScope?

When looking at controllers, I noticed that $scope includes $root. Can you explain what $root is and how it differs from the $rootScope that can be injected into the controller? ...

Javascript troubleshooting: Confusion with Radiobuttons and Checkboxes 'checked' status

My Javascript code utilizes JQuery to generate quizzes with free text, radio buttons (single choice), and check boxes (multiple choice) questions. These quizzes are created using a web interface styled with Zurb - Foundation and serialized in JSON format. ...

How to populate the space beneath the `AreaChart` curve in `recharts` when data includes positive and negative values

How can I modify my chart, created using the recharts library in JavaScript, so that the area under the curve fills to the bottom of the visible area instead of stopping at zero? This is how it currently looks: https://i.sstatic.net/CCHXu.png My goal is ...

Struggling to sift through words within the strainer

I attempted to use the toLowerCase method for filtering words and domain names, but I keep receiving an empty array. I used the toLowerCase method to ensure that data containing capital letters or searched by capital letters are converted to lowercase. Bel ...