Using a for loop to iterate through a JSON object in JavaScript

As a beginner in JS, I am attempting to iterate through the given JSON data:

myLogger - myLogger - JSON ARRAY - {"dummmysetsJSONArr":[{"entryID":"1","distance":"100","calories":"50"},{"entryID":"2","distance":"200","calories":"100"},{"entryID":"3","distance":"300","calories":"150"},{"entryID":"4","distance":"400","calories":"200"},{"entryID":"5","distance":"500","calories":"250"},{"entryID":"6","distance":"600","calories":"300"}],"success":1}

However, the output on my console is not as expected and shows:

myLogger - undefined - undefined - undefined

I have tried various solutions found at this source but none of them seem to work for me.

This is how I have attempted using a for loop:

    for (var key in jsonarry) {
      if (jsonarry.hasOwnProperty(key)) {
        myLogger(jsonarry[key].entryID + " - " + jsonarry[key].distance + " - " + jsonarry[key].calories);
      }
    }

    /*
    for (var key in jsonarry) {
      if (jsonarry.hasOwnProperty(key)) {
        myLogger(jsonarry[0].entryID + " - " + jsonarry[1].distance + " - " + jsonarry[2].calories);
      }
    }
    */

Below is my complete JavaScript code:

    google.load("visualization", "1", {packages:["corechart"]});

google.setOnLoadCallback(drawVisualization);

function drawVisualization() {

  var req = false;
  var jsonarry;

  try {
      // most browsers
      req = new XMLHttpRequest();

      myLogger("myLogger - XMLHttpRequest() created");
  } catch (e){
      // IE
      try{
          req = new ActiveXObject("Msxml2.XMLHTTP");

          myLogger("myLogger - req = new ActiveXObject(Msxml2.XMLHTTP);");          
      } catch (e) {
          // try an older version
          try{
              req = new ActiveXObject("Microsoft.XMLHTTP");

              myLogger("myLogger - req = new ActiveXObject(Microsoft.XMLHTTP);");               
          } catch (e){

          }
      }
  }

  if (!req) { 
    myLogger("req === false");
  } else {

    myLogger("req === true");
  }

  // Use onreadystatechange property
  req.onreadystatechange = function() {

       //myLogger("myLogger - req.onreadystatechange = function(){");

      if(req.readyState == 4) {

          myLogger("myLogger - req.readyState == 4");

          if(req.status === 200) {

            myLogger("myLogger - req.status === 200");

            jsonarry = req.responseText;

            myLogger("myLogger - JSON ARRAY - " + jsonarry);

            myLogger(" ------------- ");

            var obj = JSON.parse(jsonarry);

            myLogger("jsonarry.length == " + jsonarry.length);

            for (var key in jsonarry) {
              if (jsonarry.hasOwnProperty(key)) {
                myLogger(jsonarry[key].entryID + " - " + jsonarry[key].distance + " - " + jsonarry[key].calories);
              }
            }

            /*
            for (var key in jsonarry) {
              if (jsonarry.hasOwnProperty(key)) {
                myLogger(jsonarry[0].entryID + " - " + jsonarry[1].distance + " - " + jsonarry[2].calories);
              }
            }
            */
          } else {
            myLogger("myLogger - req.status == " + req.status);
          }

          //return req.status === 200 ? success(req.responseText) : error(req.status)
      } else {
          myLogger("myLogger - req.readyState != 4 i.e. req.readyState === " + req.readyState);
      }
  }

  req.open("GET", 'http://www.dummyurl/dbread.php', true);

  req.send(null); 
}

function myLogger(content) {
    if (window.console && window.console.log) {
        console.log("myLogger - " + content);
    }
}

Answer №1

When parsing the JSON string, ensure that you loop through the parsed value instead of looping through the JSON string itself.

var obj = JSON.parse(jsonarry);

myLogger("jsonarry.length == " + jsonarry.length);

for (var key in jsonarry) {
    if (jsonarry.hasOwnProperty(key)) {
        myLogger(jsonarry[key].entryID + " - " + jsonarry[key].distance + " - " + jsonarry[key].calories);
    }
}

Make sure to structure your code like this:

var obj = JSON.parse(jsonarry);

myLogger("jsonarry.length == " + jsonarry.length);

for (var key in obj) {
    if (jsonarry.hasOwnProperty(key)) {
        myLogger(jsonarry[key].entryID + " - " + jsonarry[key].distance + " - " + jsonarry[key].calories);
    }
}

Remember, it's important to iterate through the array inside the object rather than directly looping through the object itself.

Answer №2

When working with the parsed JSON result assigned to obj, remember to avoid using the raw JSON text from jsonarry

It's important to note that "dummmysetsJSONArr" is actually an array of objects.

Here's a suggested approach:

for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
           var list=obj[key];
           list.forEach(function(item){
               myLogger(item.entryID + " - " + item.distance + " - " + item.calories);
           });
      }
 }

Additionally, it's best to refrain from altering variable names like jsonarry as it could lead to confusion down the line.

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

Retrieve all references to child elements in React

I am working on a component that renders dynamic children, and I need to assign a unique ref to each child (e.g. ref={'childID' + index}) After the children have been loaded, I am looking for a way to loop through them and access their refs. Is ...

Can you explain the difference between CDN and ESM builds in vue.js?

According to the Vue.js documentation, there are differences in syntax depending on whether you are using the CDN or ESM build of Vue.js. What is the significance of having two different builds and how does it result in a difference in usage syntax? Infor ...

Testing actual HTTP requests in unit and integration tests with AngularJS

Attempting a request that was not mocked using $httpBackend.when in an Angular 1.x unit/integration test will lead to an error: Error: Unexpected request: GET /real-request Is there a way to perform actual HTTP requests with ngMock and the Karma+Jasmin ...

What methods can I use to transfer data from one domain to another domain utilizing Ajax JSONP?

Example: The URL of my site is "http://localhost:54887/CustomOrdering.html", but I want to retrieve data from another site "http://localhost:27746/Orders.aspx". In order to do this, I have implemented the following code in my CustomOrdering.html: function ...

Building a Timekeeping Tool with Javascript

I am interested in creating a timer/stopwatch using JavaScript for a specific scenario: When the user clicks the "Play" button, the stopwatch will start counting, and when they click "Pause," it will stop. The difference between the start and end times wi ...

Deactivate JQuery star rating plugin after user has voted

I've integrated the JQuery star rating plugin (v2.61) from into my project. Everything is working smoothly, but I am looking for a way to disable the stars once a user has voted. Currently, users are able to select their rating and submit it through ...

The website content is not visible on Internet Explorer version 10

Issue with Internet Explorer 10 I recently completed a new website for our company: . However, I am encountering some challenges with the site when viewed on IE 10 on Windows 7. For some reason, a large portion of the text is not displaying properly in IE ...

Automatically generated error notifications for Express-Validator

I am looking to implement an Express API and incorporate request input validation using express-validator. Here is my current validation middleware: protected validate = async (request: Request, response: Response, next: NextFunction): Promise<void> ...

Parsing JSON data using ntlm security in PHP

<?php $json_data = file_get_contents("https://user:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2d5d4c5e5e5a425f496d4942404c444c4146470b434547">[email protected]</a>"); if (empty($json_data)) { echo "un ...

Filtering an array of objects in React based on user input

(React Challenge) Imagine we have an array of objects structured like this: const books = [ { author: "Marcel Proust", title: "In Search of Lost Time", pageNumber: 123, }, { author: ...

Navigating JSON data within JavaScript utilizing a for loop

Issue Overview: My challenge involves handling JSON data returned from Python to JavaScript. I aim to iterate through the JSON structure and display the data elements in an HTML table. Code Snippets: 1] JSON received from Python -- {'data_for_user ...

The first parameter needs to be either a string, a buffer instance, or a uint8array. Null received

Encountering an error with my Node.js code and I'm not sure how to fix it. The error message reads: "First argument must be of type string or an instance of buffer or uint8array. Received undefined" I admit that I am new to Node.js and would apprecia ...

Unable to retrieve file path from image selection in JavaScript by clicking on a button

I am trying to create a simple browsing feature that only accepts images. However, after clicking the button, I am unable to retrieve the full path in JavaScript. All I can get is the filename. JavaScript <script type="text/javascript"> functio ...

Is there a feature similar to Nuxt.js' auto-register in Next.js?

My Journey as a Beginner Being a beginner in the tech world, specifically in full-stack development (although I'm about 8 years behind), I find myself grappling with the decision of what to focus on learning. Vue and Nuxt.js are fantastic technologi ...

Tips for determining the minimum value within an array of objects across multiple keys using a single function

I am currently tasked with the challenge of determining the minimum value from an array of objects that contain multiple keys. My ultimate goal is to identify the minimum value among all keys or specific keys within the objects. For instance var users = ...

Connect to a node.js server from a different network

Looking to set up a basic live chat using node.js, socket.io, and express. Managed to get it working on my local network, but wondering if there's a way for someone from another internet connection to connect without me needing to pay for server space ...

Saving JSON variable as file in a Bash script

My current challenge involves utilizing twurl on Ubuntu's command line to access the Twitter Streaming API and then parsing the resulting JSON data using this particular processor. I've managed to construct a command that successfully retrieves t ...

Angular 6: Dealing with Type Errors in the HttpClient Request

I am encountering issues with my services. I am attempting to retrieve a list of media files (generated by NodeJS, which generates a JSON file containing all media items). Although I can successfully fetch the data, I am facing an error stating "Property & ...

Maximum number of days that can be selected with Bootstrap Datepicker

I currently have a datepicker set with the multidate option and I am looking to specify a maximum number of days that users can select, say 5 days. Once a user has selected 5 days, any additional days should become disabled dynamically. How can this be a ...

What is the best way to set multiple headers and change the content type when needed?

I am struggling with a function that cannot be overridden: getHtml:function(aURL,aPostData,aHeaders,aMethod){ this.xhr = new XMLHttpRequest(); var tmp=this; this.xhr.onreadystatechange=function(){ tmp.onStateChange(); }; if(aPo ...