Having trouble retrieving properties from a JavaScript JSON object?

I am currently working with a JSON object that contains properties for MAKEs, MODELs, YEARs, STATEs, PLATEs, and COLORs. There are 4 instances of each property within the object:

Object {MAKE1="xxx ", MODEL1='xxx', YEAR1='xxx', STATE1='xxx', PLATE1='xxx', COLOR1='xxx', MAKE2='xxx', MODEL2='xxx' ,..., MAKE3='xx',..., MAKE4='xxx',...,COLOR4='xxx'}

In my JavaScript code:

 function displayPP() {
            $.getJSON('/ipad/api/formpp/' + personId + '/getmemberlatestpp', function(data) {

                for (var index=1; index<5; index++) {
                    $('#ppBody').append('<tr>');
                    var MAKE = 'MAKE' + index, MODEL = 'MODEL' + index, YEAR = 'YEAR' + index, STATE = 'STATE' + index, PLATE = 'PLATE' + index, COLOR= 'COLOR' + index;
                    var HTML = '<td>' + data.MAKE + '</td><td>' + data.MODEL + '</td><td>' + data.YEAR + '</td><td>' + data.STATE + '</td><td>' + data.PLATE + '</td><td>' + data.COLOR + '</td>';
                    $('#ppBody').append(HTML);
                    $('#ppBody').append('</tr>');      
                }                   
            });
    }

After running the code, I noticed that all the JSON properties returned as undefined. Can someone explain why this is happening? When accessing specific properties like data.MAKE1, data.MAKE2, etc., it works fine.

Answer №1

When using <code>var foo = "X"; data.foo
, it will refer to the property named foo and not the property named X.

If you wish to use a variable to represent a property name, square bracket notation must be used (taking a string instead of an identifier).

data[foo]

It is advised to avoid having items with similar names except for a numerical counter at the end. It is recommended to use appropriate data structures:

[ 
    { 
        "make": "xxx", 
        "model": "xxx", 
        "year": "xxx", 
        "state": "xxx", 
        "plate": "xxx",
        "color": "xxx"
    },
    { 
        "make": "xxx", 
        "model": "xxx", 
        "year": "xxx", 
        "state": "xxx", 
        "plate": "xxx",
        "color": "xxx"
    }
]

Answer №2

To retrieve your property values, utilize bracket notation with a string input as demonstrated in the example below:

data['MAKE' + index]

Answer №3

When defining a variable, such as MAKE = 'MAKE1', make sure to use it correctly when accessing its value from an object like data.MAKE. Using dot notation in this case will look for a property named 'MAKE' within the data object. To access a variable using a string, you should utilize bracket notation instead, like data[MAKE].

Provided below is the updated version which rectifies all incorrect attempts at referencing properties with dots:

function displayPP() {
    $.getJSON('/ipad/api/formpp/' + personId + '/getmemberlatestpp', function(data) {
        for (var index=1; index<5; index++) {
            $('#ppBody').append('<tr>');
            var MAKE = 'MAKE' + index, MODEL = 'MODEL' + index, YEAR = 'YEAR' + index, STATE = 'STATE' + index, PLATE = 'PLATE' + index, COLOR= 'COLOR' + index;
            var HTML = '<td>' + data[MAKE] + '</td><td>' + data[MODEL] + '</td><td>' + data[YEAR] + '</td><td>' + data[STATE] + '</td><td>' + data[PLATE] + '</td><td>' + data[COLOR] + '</td>';
            $('#ppBody').append(HTML);
            $('#ppBody').append('</tr>');      
        }                   
    });
}

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

Looking for a node.js asset manager for converting coffeescript, jade, and stylus files to JS and CSS?

I specialize in using coffeescript, jade, and stylus for my projects. My task involves creating two separate "one page apps" where I need to include all assets within the initial payload. My goal is to consolidate, compile, and merge all coffeescript fil ...

Issue with ThreeJS CSG when trying to intersect extruded geometries

element, I'm facing a challenge with extracting multiple views and intersecting them to form a final polygon. The issue arises when there are floating extra parts in the result that are unexpected. My goal is to find a solution to detect these extrane ...

JavaScript 'await' throws error 'then is not defined'

Just starting out with async programming and I've noticed a common issue in similar threads - the problem of not returning anything. However, in my case, I am facing a different error message 'Cannot read property 'then' of undefined&ap ...

I am struggling to make my button hover effects to function properly despite trying out numerous suggestions to fix it

As a newcomer, this is my first real assignment. I've managed to tackle other challenges successfully, but this one seems a bit more complex and I'm struggling to pinpoint where I'm going wrong. Despite googling various solutions, none of th ...

Whenever I launch my React web application, I consistently encounter a white screen when attempting to access it on my phone

After developing my web app in ReactJS and deploying it to the server, I've noticed that sometimes the screen appears white for the first time after deployment. However, when I reload the page, the app runs normally. I am hosting the backend and front ...

Tips on retrieving JSON data in a Bottle (Python framework) using a Jquery script

I'm currently facing an issue where I am sending a POST request with JSON data using AJAX jQuery, expecting to receive it on my API server built with Bottle. However, the JSON data is being sent from the client side but isn't being received by th ...

What is the best way to activate CSS filters on VueJS once the project has been compiled?

While working on a Node server locally, my SVG filter functions properly. However, once I build the project and run it on a server, the filter stops working. This VueJS project is utilizing Webpack as its build tool. The process of building the app invol ...

The Angular service "this" is altering the context of the window object

I must have made a mistake somewhere and I know I am overlooking something obvious. The aim is to create a service that provides basic authentication features such as login, logout, and checking if a user is logged in or not. Upon loading the page, I veri ...

"Troubleshooting the issue of AngularJS $http patch request failing to send

The information is successfully logged in the console when passed to replyMessage, but for some reason, the API does not seem to be receiving the data. Is the input field perhaps empty? replyMessage: function(data) { console.log(data); ...

Is there a way to incorporate hyperlinks into the Application column of my v-data-table component?

When loading data table from the database, I have included links along with the names of the Applications. However, I only want to display the Application name and open the corresponding link when clicked. headers: [ { text: 'Name&a ...

Nextjs API call ended without a response being sent

I am currently facing a challenge in my NextJS project as my endpoint API does not support multiple calls, and I am looking to implement a data refresh every 3 minutes from the original source. To achieve this, I have integrated an API in NextJS by creati ...

Failing to retrieve the file instance upon completing the upload process to cloudinary using nestjs

I am attempting to retrieve the secure file URL provided by Cloudinary after successfully uploading the asset to their servers. Although I can upload the file to Cloudinary, when I try to view the response using console.log(res), I unfortunately receive &a ...

dynamically import a variety of components in vue.js and nuxt depending on certain conditions

Is there a way to implement dynamic imports for all 3 components in this scenario? Each component has different props, so using the switch option in the computed method is not feasible. I have come across solutions for using a single component dynamically ...

Ways to differentiate between a desktop browser width of 1024px and a tablet width of 1024px with the help of jquery

So here's the issue I'm dealing with: I have scroll-based animation functions set up for desktop browsers, and different animations in place for tablet browsers. The challenge is to make these functions work on a desktop with a 1024px dimension. ...

Utilizing relative URIs in Node.js request library

I've encountered an issue with my code where node.js is unable to resolve the url: const request = require('request') const teamURL = `/users/${user._id}/teams`; const req = request({ url: teamURL, json: true }, function(error, ...

Is there a way to modify page URLs without causing a refresh, regardless of browser?

Despite my extensive searches on various online platforms, including stackoverflow, I have yet to come across a satisfactory answer to my question. While I find the window.history.pushState() and window.history.replaceState() methods quite user-friendly, ...

What is the best way to import the L module from the "leaflet" library in Next.js?

Implementing Leaflet into my Next.js development posed a challenge as it did not support server side rendering (SSR). To address this, I had to import the library with SSR disabled using the following approach: import React, {Component} from "react&qu ...

Loading events for a fullCalendar in node.js using the jade library

I successfully integrated fullCalendar into my nodeJS application using jade and Express, and I have managed to load the calendar. Within the jade file, I pass an array containing events information. How can I display these events on the calendar within th ...

Designing a menu header against a specific background color resulting in misalignment

I have been working on creating a menu header for my website. If you would like to take a look, here is the link to my jsfiddle page. Unfortunately, I am facing an issue where all my images and text should remain in that grey color scheme but somehow it& ...

The output generated by javax.json is often difficult to decipher and understand

I have written a Java class with two attributes that I convert to JSON using a specific method. Following the advice from another source, here is my implementation: Return JSONArray instead of JSONObject, Jersey JAX-RS public String toString(){ // Ut ...