Looping through nested JSON values using a "for" loop in JavaScript

How can I iterate through a JSON file to retrieve the values of total and first_record? The specific key is:

json.STATION[0].OBSERVATIONS.precipitation[0].total

My goal is to display the result in the following format:

[20180116, 0.8], [20180117, 0.0] . . .

Despite trying different methods, I keep getting an output with undefined as the best result. Below is a snippet from my work on JSFiddle where the JSON data is generated using the Mesowest.net API.

Once I resolve this issue, I intend to plot these values using Highcharts. Thank you for your help.

const data = {
  "UNITS": {
    "precipitation": "Inches"
  },
  "STATION": [{
    "STATUS": "ACTIVE",
    "MNET_ID": "25",
    "PERIOD_OF_RECORD": {
      "start": "20000120",
      "end": "20180121"
    },
    "ELEVATION": "6340",
    "NAME": "BOGUS BASIN",
    "RESTRICTED": false,
    "STID": "BOGI1",
    "ELEV_DEM": "6362",
    "LONGITUDE": "-116.09685",
    "STATE": "ID",
    "OBSERVATIONS": {
      "precipitation": [{
        "count": 23,
        "first_report": "20180115",
        "interval": 1,
        "report_type": "precip_accum",
        "last_report": "20180115",
        "total": 0.0
      }, {
        "count": 24,
        "first_report": "20180116",
        "interval": 2,
        "report_type": "precip_accum",
        "last_report": "20180116",
        "total": 0.2
      }, {
        "count": 24,
        "first_report": "20180117",
        "interval": 3,
        "report_type": "precip_accum",
        "last_report": "20180117",
        "total": 0.0
      }, {
        "count": 24,
        "first_report": "20180118",
        "interval": 4,
        "report_type": "precip_accum",
        "last_report": "20180118",
        "total": 0.0
      }, {
        "count": 24,
        "first_report": "20180119",
        "interval": 5,
        "report_type": "precip_accum",
        "last_report": "20180119",
        "total": 0.8
      }, {
        "count": 24,...
<p id="demo"></p>

Answer №1

At the start, within your for loop, you are referencing

data.STATION[0].OBSERVATIONS.precipitation.total.length
, but the total component is not actually defined there. It should be precipitation[0].total in order for it to hold any value. Even then, it's not an array. You simply need:

data.STATION[0].OBSERVATIONS.precipitation.length

In terms of coding style, consider storing that information in a variable to avoid repetition and potential errors:

const records = data.STATION[0].OBSERVATIONS.precipitation;

Additionally, instead of repeatedly assigning the same value to a variable, which will only retain the last value at the end, you should store them in an array.

const totals = [];
for (let i = 0; i < records.length; i++) {
  totals.push(records[i].total);
}

If you require both total and first_report, you can either use parallel arrays:

const totals = [];
const firsts = [];
for (let i = 0; i < records.length; i++) {
  totals.push(records[i].total);
  firsts.push(records[i].first_record);
}

or create an array of arrays:

const results = [];
for (let i = 0; i < records.length; i++) {
  results.push([records[i].total, records[i].first_record]);
}

Check out this functional example:

const data = {
   // Sample JSON data object here
};

const records = data.STATION[0].OBSERVATIONS.precipitation;

const results = [];

for (let i = 0; i < records.length; i++) {
    results.push([records[i].total, records[i].first_report]);
}

console.log(results);

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

Establishing the highest allowable value limit in cleave

I've integrated cleave.js into my Vue.js project to create a date input field. Here's the option configuration I used: <cleave :options="{ date: true, datePattern: ['m', 'd','Y'] ...

Troubleshooting Event.target Problem in Firefox 6

When working in Firefox 6, I encountered an issue while trying to identify the target element on which the event occurred. Instead of displaying the desired element, it was showing as undefined in the alert message. Utilizing the Firebug tool for debugging ...

Issue with IntelliJ: TypeScript Reference Paths Are Not Relative

I am currently using IntelliJ as my IDE, but I am facing an issue with configuring gulp-typescript to compile my typescript code. The problem arises from the fact that IntelliJ does not treat my reference paths relatively, instead it references them from m ...

Create a JavaScript object containing placeholders and another JavaScript object that holds the substitutions to be used

I have a placeholder object named ${var_name} { "name": "${title}", "description": "${description}", "provider": { "@type": "Organization" }, "hasInstance": [ ...

Having Difficulty Applying a Background Color to a Class in Bulk

I am working on a unique HTML canvas for pixel art, which is created using a table made up of various divs all sharing the "pixel" class. I want to add a clear button that can reset the entire canvas, but changing the background color of each individual di ...

How can I use jQuery to check a checkbox without triggering its bound event?

I've created a custom checkbox that will log its value to the console, and I'm trying to add a button that can tick the checkbox without triggering the checkbox event. This is purely for educational purposes. $(document).on('click', ...

Troubleshooting Tips: Investigating a Service Call in AngularJS 2 using ES6 Syntax

MY DILEMMA: I have recently started learning Angular2 and found myself wanting to debug a service call. The service appears to have been properly called, as evidenced by the view display. However, when trying to log the content of the variable holding t ...

The integration of Google Translate with Javascript on HtmlEditorExtender is experiencing difficulties and is not functioning properly

I implemented the use of a text box with ajaxtoolkit HtmlEditorExtender (Rich textbox) to translate English to Gujarati using Google translation Javascript. The translation function works perfectly with the regular text box, but encounters issues when used ...

Retrieve only the initial tag content using jquery

My goal is to extract the "22" from the following code... <div class="left"> <a class="count-link" href="http://url1.com"> <span>22</span> users </a> <a class="count-link" href="http://url2.com"> <span>10</span ...

Display or conceal form elements depending on the JSON response

Upon making an api call, a json Response is received with the following structure: {"Field":"Amount","FieldName":"Amount","FieldType":"Numeric","MaximumLength":128,"MinimumLength":0,"Options":"Mandatory"} This api call yields between 5-10 of these object ...

In a carousel slider, the height and width of divs are not set to specific dimensions

For a code snippet, you can visit this link: here The html: <html lang="en"> <head> <link href="https://fonts.googleapis.com/css?family=Lato:400,400i,700,700i|Merriweather:300,400,700" rel="stylesheet"> <link href="https://ma ...

Selecting the optimal data structure: weighing the benefits of using boolean check versus array .include (balancing performance and redundancy

My objects can have one or more properties assigned, with a total of 5 different properties in my case. To illustrate this, let's use a simple movie example where each movie can be assigned from 5 different genres. I have come up with two methods to ...

What causes AsyncStorage to lose one value while another value remains intact?

My last session id is stored using AsyncStorage, but for some reason it loses a specific value and I can't figure out why. I created an app that should automatically select the last chosen group on startup. However, after restarting the app, AsyncSto ...

Using PHP to interact with JSON APIs

I have tried various solutions and read through other posts to fix a similar issue, but unfortunately, I haven't found a resolution. My current task involves using the following API: which provides the following data: { "owner": "IPMA", ...

Is there a way to update protractor.conf.js configurations using the command line?

Currently, I have set up Protractor to run on our integration server. In the protractor.conf.js file, I have configured the multiCapabilities as follows: multiCapabilities: [{ 'browserName': 'firefox', 'platform': &a ...

Tips for utilizing the jQuery selectbox plugin on multiple elements within a single page

On my webpage, there are 3 select boxes that I want to customize using a jQuery selectbox plugin. However, the issue I'm encountering is that the plugin only works on the first select box and the others remain unchanged. Does anyone know why this mig ...

Parse JSON data and save information into PHP arrays

My JSON data has a specific structure that I need to reorganize. { "1":{"Itemname":"dtfg","unitprice":"12","Qty":"4","price":"$48.00"}, "2":{"Itemname":"kjh","unitprice":"45","Qty":"7","price":"$315.00"}, "3":{"Itemname":"yjk","unitprice":"76","Qty":" ...

Clearing Time Field Input in Safari

Recently, I've been utilizing the following HTML input element: <input type="time"> While testing it in both Chrome and Safari, I noticed that the clear field (cross button) is absent when using Safari. How can I make the cross button appear i ...

What can be used in place of Subject.prototype.hasObservers?

I have recently come across the version 4 of RxJS, and noticed that the method hasObservers on Subjects seems to have been removed. I am now faced with the challenge of migrating, as this removal is not documented on the migration guide. hasObservers: fun ...

The ng-click functionality is not functioning as expected within the directive

Take a look at this snippet of my HTML: <section ng-controller="GalleryController as gallery"> <nav footer-directive></nav> </section> This is the GalleryController I'm using: angular .module('myapp') ...