Navigating deeply nested arrays while parsing JSON in JavaScript

I'm currently working on parsing JSON data with JavaScript, but I've hit a roadblock when trying to access the value that is part of the first PWER object (the value changes and I simply want to display it on the webpage). Additionally, the '1452520496000' portion also changes based on time. As someone new to JavaScript and JSON, I find the examples I have come across during my research to be relatively straightforward compared to this particular case where I need to access the PWER in "cid": "PWER".

Below is an excerpt of the JSON output received from the API:

[
{"cid":"PWER",
 "data":[{"1452520496000":568}],  
 "sid":"144",
 "units":"kWm",
 "age":5
 },

{"cid":"MOTN",
 "data":[{"1452520489000":0}],
 "sid":"910",
 "units":"S",
 "age":12
 },

{"cid":"LGHT",
 "data":[{"1452520489000":19.09}],
 "sid":"910",
 "units":"L",
 "age":12}
 ]

In order to tackle this challenge, I have adopted code snippets from the example provided here as a foundation for the HTTP GET request while I figure out how to parse the JSON data efficiently. Here's what I have managed to put together so far:

<div id="main"></div>

<script>
var xmlhttp = new XMLHttpRequest();
var url = "URLGoesHere";

xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        myFunction(xmlhttp.responseText);
    }
}
xmlhttp.open("GET", url, true);
xmlhttp.send();

function myFunction(response) {
    var arr = JSON.parse(response);

    var out = arr[0].data[0];

    document.getElementById("main").innerHTML = out;
}
</script>

The problem I am facing is that instead of displaying the desired result, my page shows [object Object].

To troubleshoot, I've been using the console:

console.log(arr[0]);

Object {cid: "PWER", data: Array1, sid: "144", units: "kWm", age: 5}

This confirms that the API token is successfully accessed and data is being retrieved.

In order to dig deeper into the retrieved data, I check the contents of 'Array1' within 'data':

console.log(arr[0].data);

[Object]
0: Object
length: 1
__ proto __: Array[0]

My next step involves trying to access the object at index 0:

console.log(arr[0].data[0]);

Object {1452520496000: 568}

The desired value of 568 is present, however, I am unable to access it due to the ever-changing nature of the '1452520496000' parameter. What would be the most effective approach to accessing this value?

Answer №1

To retrieve the specific key you need, you can utilize the Object.keys(object) method.

var information = arr[0].data[0];
var keysList = Object.keys(information);
console.log(keysList[0], information[keysList[0]]);

Answer №2

let firstData = arr[0].data[0];

console.log(firstData[ Object.keys( firstData )[ 0 ] ] );

Retrieve all the keys from firstData by using Object.keys(), save them in an array, and then access the key at the first index.

Answer №3

JSON operates based on the key-value pair concept. The object currently being utilized does not adhere to the JSON format.

"information":[{"1547283021000":673}],  

You have the option to utilize the above data in two different formats:

  1. Include both values within an array
    "information":["1547283021000", "673"],
  2. Utilize specific keys
    "information":{"key1":"1547283021000", "key2":"673"},

If you wish to stick with the same format, here is a method I discovered to parse your JSON

var d = 'your json';
var parsedObjects = $.parseJSON(JSON.stringify(d));

Convert the JSON into a string and then proceed with parsing it.

Answer №4

amy2874 provided an excellent solution. Another option is to iterate through the POJO in 'data' using a simple loop. Here's one way to do it with a basic for loop (but there are more efficient looping methods available):

var data = arr[0].data[0];
var result;
for (var property in data) {
    result = data[property];
}

Keep in mind that if there are additional keys within the 'data' object, you'll need to include error handling before assigning a value to 'result'. For example, if the object looks like this:

{
    ...
    data: [{ "foo": "someval", "1452520496000": 568, "bar": "someotherval" }]

In this case, you should implement some validation logic inside the loop to ensure you're targeting the correct key. It's also advisable to break out of the loop as soon as you've found the desired key for performance reasons.

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

Utilize JavaScript to parse JSON containing multiple object settings

After receiving the server's response, I am looking to extract the "result" from the JSON data provided. This is my JSON Input: { "header":{ "type":"esummary", "version":"0.3" }, "result":{ "28885854":{ "uid":"28885854", "pub ...

When package.json is imported, files are not compressed

Currently, I am working on developing a cli package and when it comes to displaying the version, I am utilizing the version imported from package.json. Upon running tsc, the structure of the dist folder appears as follows: /dist --/package.json --/README. ...

What improvements can I implement to enhance the clarity and functionality of this form handler?

As a beginner working on my first Next.js app, I'm facing some challenges that seem more React-related. My app allows users to add and edit stored food items and recipes, requiring me to use multiple submit form handlers. Each handler involves: Che ...

Eliminating redundant files in the upload section

Currently, I am using lodash clonedeep for the purpose of uploading files. I managed to write a function that prevents users from uploading identical files. However, I have encountered an issue where if I delete a file after uploading it, it remains in th ...

Why is my React app opening in Google Chrome instead of the API?

I have a link in my React app that is supposed to open a PDF in another page, but for some reason Google Chrome is redirecting me to the React application instead of opening the API endpoint that renders the PDF. The URL for the PDF is /api/file/:_id and m ...

What is the best approach for transforming a string that resembles a dictionary into an actual dictionary?

Here is an example of a dictionary-like string: str = "Access AR1:\n\tTargets: \n\t\tManagement Name:csw_1\n\t\tObject Name:csw_obj_1\n\t\tdetails:103\n\t\tManagement Name:csw_123&b ...

Merge array and object destructuring techniques

What is the correct way to remove a value from an array? const ?? = { text: ['some text'] }; ...

Exploring the functionality of OpenLayers 5: Removing a map layer with a checkbox

I need assistance with removing a layer from a map using openlayers 5. I have successfully added the layer to the map using a checkbox. What I am looking for is that when the checkbox corresponding to the layer is checked, the layer will be displayed on th ...

I'm puzzled by the error I'm encountering with my PHP cURL request to the GitHub API, especially considering it functions perfectly in Postman. What could

Using a valid OAuth token, I am able to successfully retrieve information about my private repos from GitHub API by making requests with the following headers in Postman: Accept: application/vnd.github.v3+json Authorization: token 5c67da5c67f5d67ac5ff5ac ...

AngularJS UI-Router: Utilizing Optional Parameters

.state('registration', { url:'/app/registration/:ref', templateUrl: 'partials/registration.html', }) This is my configuration for routing using ui-route. It functions properly when I go to localhost:80/r ...

Adding an item to an array in Angular 2 using JavaScript!

In my Angular2 form, I have a field that consists of an array of objects. I've successfully created a table with a Delete Row button for each row and an Add Row button using the push() and slice() methods in JavaScript. However, there's a major ...

Guide on clearing an email input field in JavaScript after it has been filled with white spaces, when setting the value to an empty string ("") does not produce the desired result

When attempting to clear an input (type="email") filled with only white spaces using JavaScript, the cleaning process does not function as expected. Check out the code snippet below (link): <input type="email" id="myEmail" placeholder="Enter e-mail" au ...

What is the best way to save a collection of image and video files using JavaScript?

I have a requirement to store lists of images and video files in JavaScript. Initially, I used the formData.append() method to store these files with keys, which worked perfectly fine. However, I encountered an issue where I was unable to delete a file us ...

Numerous JavaScript functions seamlessly integrated into HTML

I'm currently working on incorporating two sliders into my HTML code and utilizing JavaScript functions to update the values indicated by those sliders. I am facing an issue with organizing the code for the output of each slider, possibly due to how t ...

Looking to iterate through a dataframe and transform each row into a JSON object?

In the process of developing a function to transmit data to a remote server, I have come across a challenge. My current approach involves utilizing the pandas library to read and convert CSV file data into a dataframe. The next step is to iterate through t ...

I am unable to comprehend the function definition

I have familiarity with different types of JavaScript function declarations such as expression functions and anonymous functions. However, I am unsure about the syntax used in these two specific functions: "manipulateData: function (input)" and "getDataByI ...

Is it possible to trigger a Bootstrap 5.2 Popover within an "if" statement?

As part of my input validation process, I am utilizing popovers. However, I am struggling with the syntax to make it work as intended. https://jsbin.com/sufitelodo/1/edit?html,js,output The JSBin provided serves as the foundation for this issue. I am un ...

Error message "Webpack is encountering an issue stating you might require a suitable loader" appearing during React development using TypeScript

I've been struggling to set up a new project using webpack, react, and typescript. Despite my efforts, I can't seem to get it to work. I've experimented with the html loader and followed various tutorials to try and resolve the issue. Here ...

How can I show name and value pairs as columns in SQL Server?

My database has two tables structured like this: CREATE TABLE case_form ( id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, title VARCHAR(50) NOT NULL, description TEXT NOT NULL, PRIMARY KEY (id) ) INSERT INTO case_form (id, title, descriptio ...

Fixing Android Volley's onClick retry functionality issue

I am currently working on an app that heavily relies on using Volley. Throughout my app, whenever a request is made, Volley attempts to process it based on the Retry Policy settings. If an error occurs during this process, I need to display an AlertDialog ...