Retrieving data from a JSON object using a variable

{
  "data": [{
    "data": [{
      "Part": "1.75 L ICON (Glass)",
      "ProductionCounts": 1012620
    }, {
      "Part": "1.75 L Marg Mix (PET)",
      "ProductionCounts": 1003278
    }, {
      "Part": "1.75 L Authentics (PET)",
      "ProductionCounts": 457615
    }, {
      "Part": "1.0 L Margarita Mix / PET",
      "ProductionCounts": 660982
    }, {
      "Part": "other",
      "ProductionCounts": 1571985
    }]
  }],
  "dateArray": ["2011-01-01", "2011-02-01", "2011-03-01", "2011-04-01", "2011-05-01", "2011-06-01", "2011-07-01", "2011-08-01", "2011-09-01", "2011-10-01", "2011-11-01"],
  "xAxis": "Part",
  "yAxis": "ProductionCounts",
  "interestingMoments": []
}

To retrieve the value of a JSON object, the field name must be identified through xAxis and yAxis variables as it may vary each time the object is accessed.

When attempting to access jsonData.data[0].data[0].xAxis, it returns undefined instead of the actual value. It's not possible to access like this due to varying field names, so the correct way would be using a variable like jsonData.data[0].data[0].Part .

Answer №2

It is recommended to structure your data in JSON format as shown below:

var exampleData = {
  "data": [{
    "data": [{
      "Part": "1.75 L ICON (Glass)",
      "ProductionCounts": 1012620
    }, {
      "Part": "1.75 L Marg Mix (PET)",
      "ProductionCounts": 1003278
    }, {
      "Part": "1.75 L Authentics (PET)",
      "ProductionCounts": 457615
    }, {
      "Part": "1.0 L Margarita Mix / PET",
      "ProductionCounts": 660982
    }, {
      "Part": "other",
      "ProductionCounts": 1571985
    }]
  }],
  "dateArray": ["2011-01-01", "2011-02-01", "2011-03-01", "2011-04-01", "2011-05-01", "2011-06-01", "2011-07-01", "2011-08-01", "2011-09-01", "2011-10-01", "2011-11-01"],
  "xAxis": "Part",
  "yAxis": "ProductionCounts",
  "interestingMoments": []
};

exampleData.data[0].data[0][exampleData.xAxis] // Use this to access Part values
exampleData.data[0].data[0][exampleData.yAxis]  // Use this to access ProductionCounts values

Answer №3

To get the xAxis data, you can use this simple code:

console.log( jsondata.xAxis );

You can check it out here: jsFiddle

Answer №4

Give this a shot:

let info={
  "info": [{
    "info": [{
      "Item": "1.75 L ICON (Glass)",
      "AmountProduced": 1012620
    }, {
      "Item": "1.75 L Marg Mix (PET)",
      "AmountProduced": 1003278
    }, {
      "Item": "1.75 L Authentics (PET)",
      "AmountProduced": 457615
    }, {
      "Item": "1.0 L Margarita Mix / PET",
      "AmountProduced": 660982
    }, {
      "Item": "other",
      "AmountProduced": 1571985
    }]
  }, ],
  "dateList": ["2011-01-01", "2011-02-01", "2011-03-01", "2011-04-01", "2011-05-01", "2011-06-01", "2011-07-01", "2011-08-01", "2011-09-01", "2011-10-01", "2011-11-01"],
  "xAxisLabel": "Item",
  "yAxisLabel": "AmountProduced",
  "keyEvents": []
};
console.log(info.xAxisLabel);
console.log(info.yAxisLabel);

Answer №5

I suggest removing the unnecessary "data" object.

http://jsfiddle.net/turiyag/cQNPm/

After making this adjustment, the code appears more streamlined and functions correctly. Additionally, your JSON object did not pass JSLint. It is important to always validate your code using tools like JSLint before sharing it.

log("jsonData.data[0][jsonData.yAxis]: " + jsonData.data[0][jsonData.yAxis]);

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

Obtaining Input Field Value in Angular Using Code

How can I pass input values to a function in order to trigger an alert? Check out the HTML code below: <div class="container p-5 "> <input #titleInput *ngIf="isClicked" type="text" class="col-4"><br& ...

Looking for the temporary folder created by the nodejs filesystem?

After encountering path issues with writing values from a textarea to a file using fs, I turned to stackoverflow and discovered that the path should be a tmp folder. Following this advice, the terminal indicated success with the process. However, now I am ...

Preventing multiple tabs in a form with PHP

I have successfully used JavaScript to prevent a link from being opened in multiple browser tabs every time a user clicks on it. For example, if the destination of my link is Google, it will create a new tab if one does not already exist but refresh the ex ...

Obtaining a button from a dialog in Google Apps

It seems like I'm overlooking something really simple here, but I'm struggling to enable an interface button from a dialog box in Google Apps. When I try setting the disabled attribute to false in a this object under the "click" function, the bu ...

Implement an event listener in a PHP server-side file to capture the onClick event with the

I am completely new to working with Ajax. In my application, I am using ajax along with a server-side php page named Req.php to retrieve records from a database, generate a table based on those fetched records, and then display it. Now, I am looking to inc ...

Guide to verifying a METHOD GET request with Node.js and Express

Issue I've developed an API that returns an array of data when a request is made. The API URL needs to be accessed by an external team of developers. My goal is to restrict access to the /api/verily endpoint only to this specific team. Is there a wa ...

NativeScript element isn't showing up

Being relatively new to application development with NativeScript, I find myself in a situation where I need assistance in finding a solution. Drawing from my experience with PHP, I am now looking to create a template for each "page" of the application. Th ...

To maintain simplicity in my Swift code, I utilize a universal CodingKeys structure to streamline the manipulation of objects

When looking at a simplified example, I come across these two JSON strings: let jsonStringBird = """ { "identifier": "0001ABX", "name": "Doroty", "species_name": "Gorrion&quo ...

When an array is passed into a Vuex action function, it transforms into something other than just

EDIT: Added extra code in the filterEvents snippet for more context. I'm struggling to understand the behavior of my code. My goal is to pass an array into an action function within my Vuex store. However, when I return a Promise inside that action f ...

I possess a solitary div element that requires dynamic replication

I have a single container and an unspecified number of rows of data. I want to display this data on HTML cards that are generated dynamically based on the number of rows. For example, if there are 10 rows of data, I need to create 10 card elements with ea ...

What is the most effective way to iterate through an array of objects and retrieve the results in a key-value format?

I am dealing with an array of objects that may seem a bit complex initially, but I will simplify it as much as possible. Each object in the array has properties like Engineering, Environment, and others, each containing a sub-object called radars. The rada ...

Utilizing ng-repeat $index for locating an element within an array

Within my $scope, there is a property called $scope.cars, which is an array of cars. Users have the ability to delete a car from this array. When calling the delete function deleteThis, I pass the $index parameter created by ng-repeat. However, in the Ja ...

Bug in canvas rendering for Chrome versions 94 and 95

The Canvas drawing functionality in the Chrome browser seems to have some visible bugs. Here's an example of code that demonstrates this issue: const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d&apo ...

Is there a method to retrieve the subdirectories and files currently present on a given URL?

Picture having a file on your system with the following URL: I am curious if there is any software, command, or script that can retrieve subfolders/files based on a given URL. For instance: Input parameter: http://my.page/folder_1/ Output: http://my.p ...

Ways to resolve issues with queryStringParameters in an Exception

Trying to retrieve GET request parameters: An exception occurs when there are no parameters present. event = objectMapper.readTree(input); JsonNode queryParameterMap = event.findValue("queryStringParameters"); Interestingly, there is no excepti ...

What is the best way to enclose a bootstrap row within a clickable link generated by the twitch.tv API?

Recently, I completed a JSON/JavaScript project for Free Code Camp that retrieves streamer information like their logo, current status, and display name. My goal is to enclose entire Bootstrap 3 rows in hyperlinks linked to the streamers' pages, elim ...

Using jQuery to populate a select box with values from an XML file

I've come across various examples demonstrating how to achieve this task and have successfully applied others that utilize attributes. However, in the current scenario, I am working with XML data that does not contain attributes. My goal is to populat ...

Frontend experiencing issues with Laravel Echo Listener functionality

I have recently developed a new event: <?php namespace App\Events; use Illuminate\Broadcasting\Channel; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Broadcasting\PresenceChannel; use Illuminate&bs ...

Troubleshooting issue with Onchange in select HTML element within Django

I'm working with a Problems model in my project. In my Models file models.py class Problems(models.Model): Easy = 'Easy' Medium = 'Medium' Hard = 'Hard' NA = 'NA' DIFFICULTY = [ (NA ...

Canceling ongoing Angular HTTP request does not stop

Is there a way to properly cancel an $https request in Angular when a new request is triggered? Despite using allMarkersRequest.abort(), the pending request still shows up in Chrome's dev tool. What am I missing? In the code snippet below, allMarkers ...