Transform a nested JSON array into a JavaScript array

I have a JSON array that looks like this (shortened for simplicity):

[
  {
    "name": null,
    "code": null,
    "results": [
      {
        "date": "2012-04-28T06:00:00.000Z",
        "name": null,
        "value": 135,
        "unit": "MG/DL",
        "code": null
      },
      {
        "date": "2012-04-28T06:00:00.000Z",
        "name": null,
        "value": 59,
        "unit": "MG/DL",
        "code": null
      }
    ]
  },
etc, etc,
]

I need to convert this array into a JavaScript array so I can extract the date and value for plotting purposes. I've heard about using eval and JSON.parse, but I'm struggling to access the values correctly.

The JSON data is stored in a variable called labs, so I try the following:

var obj = JSON.parse(labs);
alert("obj.length="+obj.length);    // correctly shows 22 objects
for (var prop in obj) {
    if (obj.hasOwnProperty(prop)) {
        alert("prop: " +prop + " value: " +obj[prop]);
    }
}

However, the output I get is: prop: 0 value:[object Object] prop: 1 value:[object Object] and so on.

Can someone help me understand how to access the date and value fields in this scenario?

Answer №1

To access the first instance of the "date" field, use the following code:

obj[0].data[0].date

With this information, you can create nested loops for each index of 0. The first loop will iterate over obj:

for (var i = 0; i < obj.length; i++) {
    // loop body
}

The second loop will iterate over each item in the nested "data" array within obj:

var data = obj[i].data;

for (var j = 0; j < data.length; j++) {
    // loop body
}

Within these loops, you can display the specific fields you are interested in:

alert("Date: " + data[j].date + "\nValue: " + data[j].value);

Answer №2

Make sure to enclose your loop within a traditional for loop. At the moment, your data consists of an array of various objects.

for (var i=0; i<objects.length; i++) {
    for (var property in objects[i]) {
        if (objects[i].hasOwnProperty(property)) {
            alert("Property: " +property + " Value: " +objects[i][property]);
        }
    }
}

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

executing the following event in Node.js

Is it feasible to execute only a portion of the code on each iteration of the event loop in an application where requests can take a second or two? Consider the following scenario: function foo() { ...critical code... ...start processing the next ...

Upon redirection, my JavaScript codes cease to function properly and require a page refresh to resolve

Upon redirecting to another page with included JS codes, my main.html does not function properly until I refresh the page. What steps can be taken to resolve this issue? 0.html <body data-theme="b"> <div class="p2" data-role="page" id="p2"> ...

Attempting to gather data from an HTML form and perform calculations on it using JavaScript

Looking for help with extracting user input from HTML and performing mathematical operations in JavaScript. Coming from a Python background, the variable system in JavaScript is confusing to me. Can someone provide guidance on how to achieve this? <div ...

Testing inherit from a parent class in a unit test for Angular 2

Trying to create a unit test that checks if the method from the base class is being called This is the base class: export abstract class Animal{ protected eatFood() { console.log("EAT FOOD!") } } Here is the class under test: export ...

Guidance on toggling elements visibility using Session Service in AngularJS

After reading this response, I attempted to create two directives that would control the visibility of elements for the user. angular.module('app.directives').directive('deny', ['SessionTool', function (SessionTool) { ret ...

Encountering an issue when deploying a project using node, webpack, express, and mysql to Heroku. The error message states: "Uncaught ReferenceError: regeneratorRuntime is not

I've been going around in circles ever since I started this project, and now the code is all over the place. This is my first time working on a node project without using a framework, and I'm starting to regret not choosing PHP. Anyway, here&apos ...

Enable users to handle the version of a dependency in an npm package

As I develop a module that relies on THREE.js, I am exploring the most effective method to include THREE as a dependency and ensure accessibility for both the module and its users. My goal is to provide users with access to the THREE library within their p ...

Electron triggers MouseLeave event on child elements

Dealing with mouse hover events can be a bit tricky, especially when working with AngularJS in an Electron-hosted app. Here's the HTML template and script I'm using: HTML: <div id="controlArea" (mouseenter) = "onControlAreaEnter()" ...

How to handle duplicate keys in JSON parsing using Python3

Excuse my lack of experience in this area, but there's a json response that looks like this; import json jsonObj = json.loads(""" { "data": [ { "name_space": "name", "value": &q ...

Using double quotes and single quotes within a JSON string can sometimes cause conflicts and

I'm trying to understand the difference between two JSON Strings: <!DOCTYPE html> <html> <body> <h2>JSON Object Creation in JavaScript</h2> <p id="demo"></p> <script> var txt = '{"name":"Jimmy", ...

What is the best way to bundle a node module with the choice of adding submodules?

I am in the process of developing a JavaScript library that consists of a central core module and multiple optional submodules that enhance the functionalities of the core module. This library is specifically designed for the browser environment, utilizing ...

Converting a string to a dictionary in Python while preserving the order of JSON keys

After experimenting with ast.literal_eval and json.loads, I noticed that neither of them maintains the original sequence of JSON attributes when given a string. Here is an example to illustrate this point - String representation before using json.loads - ...

"Having an issue with the jQuery AJAX call where the success function is not operating as expected

I attempted to retrieve information from a database using PHP by making an AJAX call with jQuery. However, I encountered an issue where the $.ajax function was not functioning as expected. There were no error messages displayed, and the console.log('s ...

Activating autocomplete outcomes via AJAX using Cucumber/Capybara/Selenium

Whenever I try to run my tests, the autocomplete dropdown menu doesn't appear unless I physically click on the search input field. This is a Cucumber test that utilizes Selenium Webdriver, and the data is sourced from the Crafty Clicks Address Autoco ...

"Discovering the missing numbers in an array using JavaScript - a step-by-step guide

I have a series of numbers in a string, such as "3 -1 0 5". My goal is to create another string that lists the missing numbers from the original sequence once it has been sorted. For example, if the original array is sorted as [-1, 0, 3, 5], then ...

Jackson: A Guide to Extracting JSON Values

String url = "https://ko.wikipedia.org/w/api.php?action=query&format=json&list=search&srprop=sectiontitle&srlimit=1&srsearch=grand-theft-auto-v"; String result = restTemplate.getForObject(url, String.class); Map<String, String> ...

Tips for using the .innerHTML method to reference multiple indexes

How can I set the .innerHTML for multiple indexes of an array? I currently have an array let poles = Array.prototype.slice.call(document.querySelectorAll(".pole")); This array contains 9 empty divs, such as : <div class="pole" id="1"></div> ...

The Evolution of Bulma's Navigation Menu

Creating a transparent menu in Bulma has been successful for the desktop viewport: VIEW DESKTOP MENU However, when attempting to implement the same design on mobile, the menu ends up like this: VIEW MOBILE/TABLET MENU The mobile version seems to inheri ...

Avoid loading external scripts from third-party sources such as JavaScript libraries, Bing Maps API, and Lighthouse performance tool

Issue: The Bing maps API I incorporated into my assignment is loading unnecessary CSS and scripts, causing a noticeable decrease in my lighthouse scores. Is there a way to prevent third-party code (such as Bing Ads) from loading when fetching the maps for ...

Access and retrieve numerous variables from the data object sent back through an ajax request

When using jQuery to make an ajax call to an MVC controller, the goal is to return multiple variables from the controller. What is the best way to package this data in the controller and then extract it using jQuery? ...