Accurate representation of a JavaScript object using Node.js Express

I have a certain structure that I need to display on my JADE page, so I created a JSON-like object to store the data. This is how the JSON object looks like :

var dataSet1 = {
    meta: {
        "name": "Some text",
        "minimum": mini_2,
        "maximum": maxi_2,
        "currentValue": last_data_2
    },
    data: {
        "values": dataTwo,
        "corridor": {
            "x1": xc,
            "x2": yc2,
            "yw": yw2
        }
    }
};

The rendering line:

res.render('index', {
    data_to_draw: JSON.stringify(dataSet1)
});

Then I utilize this rendered data on my JADE file:

displayGraphExampleOne("#graph",
                    !{data_to_draw.data.values},
                    !{data_to_draw.meta.currentValue},
                    !{data_to_draw.meta.minimum},
                    !{data_to_draw.meta.maximum},
                    !{data_to_draw.meta.name},
                    !{data_to_draw.data.corridor.x1},
                    !{data_to_draw.data.corridor.x2},
                    !{data_to_draw.data.corridor.yw2});

Cannot read property 'values' of undefined I am encountering this error message. I am relatively new to JavaScript and trying to figure out what mistake I might be making. When I pass the data in a non-JS object format, it works fine, but I need to pass it in this manner. Thank you.

Answer №1

Avoid using JSON.stringify on the object. Simply pass the object itself to prevent attempting to access non-existent properties of a string.

Answer №2

To properly format the code, follow these steps:

var dataSet1= [

    {
        "meta": {
            "name": "Veocity variance",
            "minimum": mini_1,
            "maximum": maxi_1,
            "currentValue": last_data_1
        },

        "data": {
            "values": dataOne,
            "corridor": {
                "x1": xc,
                "x2": yc1,
                "yw": yw1
            }
        }
    }
];

Use the following code snippet:

displayGraphExampleOne("#graph",
        !{first_set}[0][0].data.values,
        !{first_set}[0][0].meta.currentValue,
        !{first_set}[0][0].meta.minimum,
        !{first_set}[0][0].meta.maximum,
        !{first_set}[0][0].meta.name,
        !{first_set}[0][0].data.corridor.x1,
        !{first_set}[0][0].data.corridor.x2,
        !{first_set}[0][0].data.corridor.yw);

Remember to include the rendering:

res.render('index', {

    first_set:  JSON.stringify([dataSet1, dataSet2, dataSet3]),
    second_set: JSON.stringify([dataSet1, dataSet2, dataSet3]),
    third_set:  JSON.stringify([dataSet1, dataSet2, dataSet3])

                    });

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

The zoom level on Google Maps adjusts based on the size of the window when it

In reference to my previous inquiry about Google maps responsive resize, I am now looking to incorporate dynamic zoom levels based on the window size. Specifically, I want the map to automatically adjust its zoom level when the browser window is resized -- ...

Using the HTML select tag to choose an integer value with AngularJS

Looking to utilize AngularJS for the first time. One of the tasks at hand is selecting an integer value using the HTML <select> tag. <select ng-model="foo.bar"> <option ng-repeat="option in options" value="{{option}}">{{option}}</ ...

eliminate the use of RelativeLayout in the Java code

In my project, I am facing an issue with utilizing web services. I encounter a scenario where the JSON web service returns nothing, and in such cases, I want to remove the relative layout that I have defined in my code. The layout consists of three relativ ...

Issue with updating input value during keyup event in Android Chrome specifically

Check out this straightforward jsfiddle: https://jsfiddle.net/gq9jga4q/33/ <input type="text" id="kbdhook" /> <div id="result" >1: </div> <div id="result2" >2: </div> <div id="result3" >3: </div> $('#kbdh ...

Simultaneously iterate through two recursive arrays (each containing another array) using JavaScript

I have two sets of arrays composed of objects, each of which may contain another set of arrays. How can I efficiently iterate through both arrays and compare them? interface items { name:string; subItems:items[]; value:string; } Array A=['parent1&ap ...

receiving incorrect request rather than the complete error message

Handling errors when using POST with the same user email can be achieved using the following code snippet (utilizing superagent): export function signUpUser(userData) { return async dispatch => { try { const currentUser = await request.pos ...

Error message: `Socket.io-client - Invalid TypeError: Expected a function for socket_io_client_1.default`

I have successfully installed socket.io-client in my Angular 5.2 application, but after trying to connect (which has worked flawlessly in the past), I am encountering a strange error. TypeError: socket_io_client_1.default is not a function at new Auth ...

There is an issue with the format of the fromdate parameter in the JSON query. It should match the following format: "%Y-%m-%dT%H:%

Below is a snippet of JSON output I'm dealing with, specifically the LastAccessedDate value. This date format is provided by AWS CLI command and unfortunately, I cannot control its structure. { "MyList": [ { "Name": &qu ...

Updating is not happening with ng-repeat trackBy in the case of one-time binding

In an attempt to reduce the number of watchers in my AngularJS application, I am using both "track by" in ngRepeat and one-time bindings. For instance: Here is an example of my view: <div ng-repeat="item in items track by trackingId(item)"> {{ : ...

Node.js scheduler library for triggering events based on time in a cron-like fashion

Currently, I am utilizing Node.js to develop a web application. My aim is to trigger events at specific times. While I am aware of using setTimeout and computing the time difference from the present moment, this method does not account for various timezone ...

I have been encountering an error consistently whenever I attempt to access the _id parameter in my angular front-end

EmployeeComponent.html: 11 ERROR TypeError: Cannot read property '_id' of undefined This is the error I encounter whenever I attempt to access the id in my front-end implementation using Angular. I have attempted incorporating ngIf, but unfo ...

Utilizing React JS to dynamically populate a table with data from an external JSON file

As a newcomer to the realm of React, I am facing challenges in displaying my JSON data in a table. class GetUnassignedUsers extends React.Component { constructor () { super(); this.state = { data:[] }; } com ...

Entering numbers using <input type="number"> does not restrict invalid inputs, while accessing "element.value" does not give me the ability to make corrections

According to the MDN documentation on the topic of <input type="number">: It is said that they have built-in validation to reject entries that are not numerical. But does this mean it will only reject non-numerical inputs when trying to ...

Eliminate redundant XML entries when using jQuery autocomplete

Does anyone know how to prevent duplicate records from appearing in a jQuery autocomplete dropdown? I am pulling data from an XML file and want to ensure that each record is unique and only displayed once. You can see the issue here ...

struggle with converting JSON string into an array from server

After receiving JSON data from the server, I attempted to convert it into an array using: JSON.parse(response.data.blocks) However, I encountered this error: SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse (<an ...

What steps can I take to resolve the "SyntaxError: Unexpected token '?' " issue when trying to connect MongoDB with Node.js?

I am currently utilizing mongodb in conjunction with nodejs. I have set up the server and established the connection to the database. However, I am encountering an issue. Server.js file const http = require('http'); require("./config/dbCon ...

Locate and retrieve all the records that contain an asterisk symbol in MongoDB

Could someone provide assistance with finding documents in MongoDB that contain the '*' character using regex? For example, the following regex (db.collection.find{value: new Regex('*')}) should retrieve all documents with '*&apos ...

Jackson encountered difficulty in the conversion of JSON to a list of maps

In my spring-boot application, I have a controller that looks like this: @RequestMapping(path = { "/multiCommunication" }, consumes = { MediaType.APPLICATION_JSON_VALUE }, method = RequestMethod.POST) ResponseEntity<Object> multiCommunicatio ...

What is the best way to utilize a JavaScript variable as a background within an inline style sheet?

I have a fun project for this evening - I am trying to make my website load a different background image every time the page is refreshed. Earlier on in this project, I managed to make the background interact with window size and screen resolution similar ...

Utilize AJAX in JavaScript file

I am encountering an issue with the following code: function inicioConsultar(){ $(function(){ $('#serviciosU').change(function(){ if ($('#serviciosU').val()!= "-1") { $.ajax({ url: "@Url. ...