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

Updating an element's HTML content from a template URL using AngularJS

Can someone help me figure out how to set the html of an element in my directive based on a dynamic template url? element.html('some url to a template html file'); rather than using element.html('<div>test</div>').show() ...

Tips for redirecting a page in React by forcing a route

Attempting to implement the guidance from this Stack Overflow solution on how to "go back home" after closing a Modal... import React, { Suspense, useState } from 'react'; import { BrowserRouter, Route, Switch, useHistory } from "react-route ...

The gear icon in the video player is not showing up when I try to change the

I am currently trying to implement a feature that allows users to select the quality of the video. I am using videojs along with the videojs-quality-selector plugin, but even though the video runs successfully, the option to choose the quality is not appea ...

The Node Express.js app is functioning properly when run locally, but displays the error "Cannot GET /" when running in a Docker container

My Node application has an Express.js server defined like this: const express = require('express') const SignRequest = require('./SignRequest/lambda/index.js') const VerifyResponse = require('./VerifyResponse/lambda/index.js') ...

Customized queries based on conditional routes - expressjs

Can we customize queries based on optional routes? app.get('/:category/:item?', function (req, res) { var category = req.params.category; var item = req.params.item; var sqlQuery = 'SELECT * FROM items WHERE category = ? AND item = ?&a ...

Having trouble retrieving the Post value ID from row table in PHP using Jquery

Although I have searched extensively for a solution to my problem, none of the suggested fixes seem to work for me. The issue is quite simple - I need to retrieve the item-id value and then POST it to del.php. However, I am unable to access the POST value ...

Is it possible to execute "green arrow" unit tests directly with Mocha in IntelliJ IDEA, even when Karma and Mocha are both installed?

My unit tests are set up using Karma and Mocha. The reason I use Karma is because some of the functionality being tested requires a web browser, even if it's just a fake headless one. However, most of my code can be run in either a browser or Node.js. ...

What is the best way to embed sections of one HTML page into another page?

Is there a method I can use to embed sections of one webpage within another webpage? The dilemma arises from the fact that the second page has a distinct style compared to my main page. Is it feasible to apply the alternate style solely to specific content ...

A guide on dynamically checking the checkbox values in each row of a table using JavaScript or jQuery

My table is dynamically populated with values from a database using the following code: var row = table.insertRow(i); i = i+1; // Insert new cells (<td> elements) at the 1st and 2nd position of the new <tr> element: var cell1 = row.insertCell ...

Is it possible to set the input form to be read-only?

I need to create a "read-only" version of all my forms which contain multiple <input type="text"> fields. Instead of recoding each field individually, I'm looking for a more efficient solution. A suggestion was made to use the following: <xs ...

When utilizing botocore.response.StreamingBody, encountering a JSONDecodeError may occur

I have encountered an issue while trying to load a payload returned by a lambda invocation, resulting in a JSONDecodeError. Below is the lambda code snippet that I am working with: from datetime import datetime metadata={} metadata["execution_info&quo ...

Dealing with Angular.js $http intercept error "net::ERR_CONNECTION_REFUSED"

Currently, I am attempting to create a universal error handler for my website utilizing $http interceptors. However, it seems that the interceptors are not functioning as intended. I have set up interceptors for 'response' and 'responseErro ...

Exploring the Power of JQuery with Hover Effects and SlideToggle

I was struggling to keep the navbar displaying without it continuously toggling when my pointer hovered over it. I just wanted it to stay visible until I moved my pointer away. <script> $(document).ready(function(){ $(".menu-trigger").hover(funct ...

Using jQuery to reference my custom attribute---"How to Use jQuery to reference My

Can you explain how to reference a tag using a custom attribute in jQuery? For example, if I have a tag like this: <a user="kasun" href="#" id="id1">Show More...</a> I want to reference the tag without using the id. So instead of using: $( ...

What is the best way to save information from an axios promise into my database on separate lines?

Having a technical issue and seeking assistance: Currently, I am encountering an issue with my axios request to the database. After successfully retrieving the data, I aim to display it in a select form. However, the response is coming back as one continu ...

Increasing space at the top with heading

As I scroll down, the header on my website remains in a static position and disappears. However, when I scroll back up, the header reappears wherever the user is on the page. While this functionality works well, I have noticed that as I scroll all the way ...

How to Use a Discord Bot to Send a Message (Step-by-Step Guide)

I am looking for a simple way to send a message using my discord bot, but everything I have found online seems too complex for me to understand and implement. require("dotenv").config(); //to start process from .env file const { Client, GatewayIn ...

User form not triggering post requests

I have a unique react blog application embedded with a form for submitting intriguing blog posts. The setup includes a server, routes, model, and controllers for fetch requests. Surprisingly, everything functions impeccably when tested on Postman. However, ...

Creating personalized functions in Object.prototype using TypeScript

My current situation involves the following code snippet: Object.prototype.custom = function() { return this } Everything runs smoothly in JavaScript, however when I transfer it to TypeScript, an error surfaces: Property 'custom' does not ex ...

Is there a way to change a model attribute in JSP based on the AJAX response?

I have a JSP page that contains the following code snippet: <li id="notifications"> <c:choose> <c:when test="${empty alerts}"> <p class="text-default">There are no Service Reminders at this time</p> ...