Browsing JSON number array by utilizing JavaScript loop

I need help writing a loop to parse through a nested number array.

The JSON file I am working with contains event dates represented by number keys. Click here for the JSON reference for startdate and end date enter image description here

Below is the JavaScript code snippet that loops through each var i = 1 or j = 1. I want to parse through the entire nested numbers from dates and store them in a variable.

$(document).ready(function () {
  $.getJSON('http://app.toronto.ca/cc_sr_v1_app/data/edc_eventcal_APR?limit=500', function (data) {
    var data = data;
    var i = 2;
    var obj = data[i].calEvent;  
    var bingname = obj.eventName;
    var j = 1;
    var startdate = obj.dates[j].startDateTime;
    var time = new Date(startdate);
    var starttime = time.getFullYear()+'-' + (time.getMonth()+1) + '-'+time.getDate();
    var name = JSON.stringify(bingname);   

    document.getElementById("bingname").innerHTML = name;


    document.getElementById("bingtime").innerHTML = starttime;


    var name = firebase.database().ref("/bing").set({
      EventName : name,
      EventStart : starttime
    });

  });
});

I need assistance implementing an incremental loop for var j. I'm having trouble because the json retrieved in obj.dates[j] does not appear to be an array. I cannot read it as a list of numbers to iterate through. Any help would be greatly appreciated.

If someone can even help me sort these dates from nearest to furthest from today, that would be genius:)

Answer №1

An array of objects will be returned, containing a callEvent object with a dates property that is an array consisting of objects with startDateTime and endDateTime properties. Here is how it will appear:

[
    {
      callEvent: {
        dates: [
          {startDateTime: '', endDateTime: ''},
          // additional objects with start- and endDateTime
        ]
      }
    },
    // more callEvent objects..
]

Your task now is to iterate through the array to access all callEvent objects and then iterate through each dates object within every callEvent.

$(document).ready(function () {
    $.getJSON('http://app.toronto.ca/cc_sr_v1_app/data/edc_eventcal_APR?limit=500', function (array) {

        // iterate through all elements in the array
        for (var i = 0; i < array.length; i++) {
            // iterate through all dates within the array 
            for (var j = 0; j < array[i].callEvent.dates.length; j++) {
                console.log(array[i].callEvent.dates[j].startDateTime)
                console.log(array[i].callEvent.dates[j].endDateTime)
            }
        }

    });
});

Answer №2

If the dates are confirmed to be in valid JSON format, you can simply retrieve the data and iterate through it like so:

for (let index=0;index<data.length;++index) {
  console.log(data[index].beginDate);
  console.log(data[index].endDate);
}

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

Unable to retrieve successful response data/status from my Node/Express server to the client application (React): "ReferenceError: response is not defined"

I have set up a simple Node/Express server and created a route to handle form data submission from React. The post request is utilizing async/await with the Fetch API. I'm unsure whether the issue lies with my server-side route or how I've implem ...

Does a DOM API exist specifically for querying comment nodes within the document?

My document contains a debugging comment that appears as follows: <!--SERVER_TRACE {...}--> Is there a method to search the DOM and access this specific node? I would prefer a vanilla JavaScript solution, without relying on any external libraries. ...

JavaScript's native innerHTML function is unable to access the content generated by Vue

I have been struggling with extracting the content from a specific div element in my HTML code. <div id="output" ref="output_data"> <h1>{{ information }}</h1> </div> I attempted to retrieve the contents using ...

Are there any advantages to using Promises and Async/Await together?

Currently, I am in the process of working through my express server controllers and transitioning from using promises to async/await. However, I find myself questioning whether this change is truly beneficial or just done for the sake of it. If the code is ...

What is the method to send an array with Ajax using ASP.NET MVC?

Below is a script I've put together to generate an array: var data_points = $("#bcc_datapoint_selection").find("input:checked").map(function () { return $(this).val(); }).get(); Output in the console log: ["3","4","6"] Script for Ajax post req ...

Issue with VueJS components not functioning as expected with routes

I've encountered an issue when using the component tag with an id of #app within the template of my components/App.vue file. Whenever I include this setup, I receive the following errors: // components/App.vue <template> <div id="app"> ...

What is the best way to incorporate an exported TypeScript class into my JavaScript file?

One of my JavaScript files is responsible for uploading a file to Microsoft Dynamics CRM. This particular JavaScript file makes use of RequireJS to reference another JavaScript file. The referenced JavaScript file, in turn, was compiled from multiple Typ ...

Instructions for utilizing HTML2PDF to create and deliver a PDF file to PHPMailer through Ajax

Trying to send a pdf generated from html2pdf (JavaScript - Erik Koopmans) to phpmailer via Ajax. Currently able to save the document to the local user's PC, but need help attaching it to an email using phpmailer. Successfully generating the pdf for s ...

<button class="fadeButton">Click me to fade in and out</

Hi everyone! I'm currently working on my website as a fun project and I have a code that displays a list of shapes. However, I'm looking to replace the fadeOut feature with a new button that, when clicked, will hide the shapes. The current code a ...

Blocking Data Events in Node.js

I recently started experimenting with Node.js and I'm grappling with the concept of non-blocking functions. I have created a server in Node.js that needs to handle multiple clients in C# through TCP connections. I want to ensure that a client does no ...

The text for the Google chart is nowhere to be found

After creating a test project using the Google Chart example, I noticed that some text from the chart is missing after adding CSS. Here is the CSS code I used: html, body { font-size: 100%; height: 100%; width: 100%; } body { background: ...

Exploding particles on the HTML5 canvas

I've been working on a particle explosion effect, and while it's functional, I'm encountering some issues with rendering frames. When I trigger multiple explosions rapidly by clicking repeatedly, the animation starts to lag or stutter. Could ...

Extracting the number of elements in an array using the simdjson C++ parser

I am currently utilizing the simdjson C++ parser. Let's say I have code similar to this: #include "simdjson.h" #include <vector> #include <iostream> using namespace simdjson; int main(void) { ondemand::parser parser; a ...

The status of the xmlhttprequest remains unchanged even after the connection has been re-established

I need to continuously send an http request until I receive a positive response. When the wifi on my laptop is active, the program exits successfully. However, if the wifi is turned on while the program is still attempting, I do not get the desired respo ...

What steps can I take to stop forms from being automatically submitted when loaded through Ajax in my Laravel 8 application?

I developed a blogging application using Laravel 8 and I am currently enhancing it by implementing comment replies with jQuery (v3.5.0) AJAX. In the file comment-form.blade.php, here is the structure: <div class="form-wrapper"> <div c ...

Arranging structures by character array (name) in C++

Looking for guidance on sorting an array of structs by the field "name" in alphabetical order with this specific struct: struct employee { char name[21], surname[21]; unsigned int salary; }employees[20]; I'm aware of sorting methods like sor ...

What is the recommended data type to assign to the `CardElement` when using the `@stripe/react-stripe-js` package in TypeScript?

I'm struggling to determine the correct type to use for this import: import { CardElement } from '@stripe/react-stripe-js'; I have successfully used the types Stripe, StripeElements, and CreateTokenCardData for the stripe and elements props ...

center text above images in flexbox when page is resized

When resizing the page, I'm facing an issue where the links overlap with the images in a flexbox layout. It seems like the padding and margin between the images and links are not working due to them not being "related" or connected. I believe I need t ...

Limit access to Google Fusion Table to specific types of maps. Eliminate Google Fusion Table for selected map formats

Currently, I am in the process of creating a web map using the Google Maps Javascript API. My objective is to display a Google Fusion Table containing buildings in Boston exclusively on a stylized map named "Buildings." When I switch to the Buildings map t ...

The checkbox is not showing the check mark accurately

I am currently working on a React form where I am trying to retrieve the status of a checkbox element from local storage using the useEffect hook. const [checkbox, setCheckbox] = useState(false); useEffect(() => { setCheckbox(localStorage.getItem(&ap ...