Utilize a for loop to load data using JSON

Here's a question for you. Take a look at my code snippet:

var data=[];
for(i=0;i<parametrTable.length;++i){
    x = parametrTable[i];
    (function(i) {
        if(i==0){
            $.getJSON("myurlwithparametr", function(json) {
                $.each(json, function(j, d){
                    data.push({"column0": d.column, "count0": d.count});
                 });
             });
         }
         else{
              $.getJSON("myurlwithparametr", function(json) {
                $.each(json, function(j, d){
                    data[j]["count"+i] = d.count});
              });
         }
         })(i);
   }

The 'data' array is being filled with individual values fetched from JSON responses. I suspect the issue lies in the asynchronous nature of the variable 'i' within the loop. Any thoughts on how to tackle this challenge?

Answer №1

Ensuring the initial JSON is loaded and processed before handling others in any order.

var data = [];
x = parametrTable[0];
$.getJSON("myurlwithparametr", function(json) { ... get first data
    $.each(json, function(j, d) { // ... process first data
        data.push({
            "column0": d.column,
            "count0": d.count
        });
    });
    $.each(parametrTable, function(i, x) { // NOTE: x is now populated here
        if (i) { // run from 1 ... end after 1st JSON is done
            $.getJSON("myurlwithparametr", function(json) {
                $.each(json, function(j, d) {
                    data[j]["count" + i] = d.count;
                });
            });
        }
    });
});

Consider this alternative for a cleaner approach:

var data = [];
$.each(parametrTable, function(i, x) { // NOTE: x = parametrTable[i]
    $.getJSON("myurlwithparametr", function(json) {
        $.each(json, function(j, d) {
            data[j] = data[j] || {};
            data[j]["count" + i] = d.count;
            if (i == 0) {
                data[j].column0 = d.column;
            }
        });
    });
});

Answer №2

This code snippet is designed to meet your requirements.

let newData = [];
parameterList.forEach((item, index) => {
    if(index === 0) {
        $.getJSON("/url/with/params?params", (json) => {
            $.each(json, (j, d) => {
                newData.push({"columnZero": d.column, "countZero": d.count});
             });
         });
     } else {
          $.getJSON("myUrlWithParameter", (json) => {
            $.each(json, (j, d) => {
                newData[j]["count"+index] = d.count
            });
        });
    }
});

Answer №3

Ensure that the calls are made in a sequential order, meaning the next call will not begin until the previous one has finished. It may be necessary to verify when each call is completed within your other code.

let dataArray = [];
fetchDataParameter(dataArray, parameterList, 0); 
function fetchDataParameter(dataArray, parameterList, index){
  const parameter = parameterList[index];
  const url = "myurlwithparameter";
  $.getJSON(url, function(json) {
    if(index === 0){  
      $.each(json, function(j, d) {dataArray.push({"column0": d.column, "count0": d.count});});
    } else {
      $.each(json, function(j, d) {dataArray[j]["count"+index] = d.count;});
    }
    if(++index < parameterList.length){
      fetchDataParameter(dataArray, parameterList, index);
    }
  });
}

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

Learn how to use Cocos2d 2.1.4 to load text, strings, and JSON in HTML

Struggling to upload a large string to my project to use as a matrix, I've run into issues trying to load a text file or json into my HTML5 project. While I've seen it can be done in 3.0 using cocos2d, I'm wondering if there's a way to ...

What could be the reason for the GET method being executed after the DELETE method in ExpressJS?

Whenever I trigger the DELETE method in my Express app, it seems that the GET method is automatically invoked right after. This results in an error within my Angular code stating that it expects an object but receives an array instead. Why is the GET meth ...

Uploading files using Multipart/form-data in Node.js and Express.js

With the removal of express.multipart from the Express 4.x library, what approach would be most effective for managing file uploads in expressjs? ...

the sequence in which a node executes a javascript function

Trying to update req.session.cart with new values for prod.quantity and prod.qtyCount in the shoppingCart field of order.save(). The issue is that orders are being saved with default quantity and qtyCount values, even though I'm setting cartProducts[ ...

Using Golang to Decode mapset

Currently, I am encountering an issue while attempting to Unmarshal mapset in a user-defined struct. The error message that persists is: json: cannot unmarshal array into Go struct field A.b of type mapset.Set[int] {<nil>} Below is a snippet of the ...

Displaying a set through an express server cookie for the client to see

New to using Express and encountering issues with sending cookies. Created a basic express app that is supposed to set a cookie in the browser. Here's the server setup: const express = require('express'); const cookieParser = require(' ...

Manually browse through images in photoswipe by clicking on them to move to the previous or next ones

Utilizing photoswipe within my mobile app has been a seamless experience. Instead of utilizing the full screen view, we are displaying images within a target div. A new requirement was introduced to hide the built-in toolbar and incorporate arrow buttons ...

When I try to import script files into my ASP.NET page, Intellisense displays the methods accurately. However, when I attempt to call one of them, an

I added a function to an existing .js file (I tried two different files) in order to make the method accessible in multiple locations without having to repeat the code. I also created a simple function just to confirm that my function wasn't causing a ...

The specified method is not recognized as a function in the ReactJS library

Within my reactJS application, there is a function that calls upon a helper function to retrieve the result of a calculation. The component looks like this: import React, { Component } from "react"; import * as d3 from "d3"; class DrawImage extends Comp ...

What steps do I need to take in order to generate a legitimate link annotation within Adobe Acrobat by utilizing Acrobat

Seeking guidance on how to embed an Acrobat Javascript within Adobe Acrobat in order to generate a link annotation. The current method involves using the "addLink" function within the document object, which triggers a Javascript action upon clicking the li ...

Navigate to the same destination with React Router Dom while passing state as a parameter

Let's talk about a scenario with a Link setup like this: <Link to={`/samelocation/${id}`} state={{ state1: 'hello' }}> This link is nested in a sub-component within the main component situated at /samelocation/:id. To ensure that the ...

Convert JSON data into any desired object

When making an API request, the response structure may look like this: { "MessageBody": { "foo" : "" } } The contents under MessageBody can vary, not limited to just foo, but always with a string value. For e ...

Is there a way to randomly change the colors of divs for a variable amount of time?

I have a unique idea for creating a dynamic four-square box that changes colors at random every time a button is clicked. The twist is, I want the colors to cycle randomly for up to 5 seconds before 3 out of 4 squares turn black and one square stops on a r ...

Incorporate Functionality into AngularJS Controller

Although I have experience with other MVC Frameworks, I am new to AngularJS and facing an issue. My controller is named "Projects" and the route is /projects. However, I want to be able to navigate to /projects/java where a new page template/view will be d ...

Transition one background image into another using background positioning

Snippet of code: https://jsfiddle.net/foy4m43j/ HTML: <div id="background"></div> CSS: #background { background-image: url("http://i.imgur.com/hH9IWA0.png"); background-position: 0 0; background-repeat: repea ...

Public directory assets not accessible

After working extensively with Node and Angular, I realized my back-end structure needed some serious attention. In an effort to streamline my process, I decided to separate the client and server components and create a reusable skeleton for future applica ...

Changing the active state of an icon when clicked in a list generated by v-for in Vue

In my Vue.js application, I have created a list of objects where each object represents a star. I want to implement a feature where a star changes color when it is clicked. However, the issue I am facing is that when I click on one star, all the stars in ...

Guide to sequentially playing multiple video objects with buffering

As I work on developing a reference player application that utilizes node.js, javascript, and HTML5, I have encountered an issue. Currently, my player successfully loads a single video and generates diagnostic data from it. However, I am striving to enhanc ...

My AJAX checkbox change event is not functioning, what could be causing this issue?

This is a sample of the code I'm working with: <form asp-action="Save" asp-controller="ClassesHeld" method="post"> <input asp-for="ClassHeldId" value="@Model.ClassHeldId" hidden /> <div class="form-group"> ...

Guide on converting this function into a computed property within Vue

Is it possible to concatenate a fixed directory path, which is defined in the data property, with a file name that is determined using v-for? I encountered an issue when attempting to do this using a computed property. The error message displayed was: ...