Patience is key for a fully completed JSON in JavaScript

I recently came across a similar discussion on Stack Overflow, but it involved using JQuery which I'm not using.

My issue is that I need to ensure my JSON data is fully loaded before calling my function. I understand the concept of using a callback, but for some reason, I can't seem to implement it correctly.

Here's a snippet of the JSON data (portion truncated for brevity):

{type: "robot", nom: "445250sup01", ville: "RENNES", departement: "35", region: "Ouest", …}
{type: "robot", nom: "445250sup02", ville: "PARIS", departement: "75", region: "Ile-de-France", …}
{type: "robot", nom: "445250sup13", ville: "ORLEANS", departement: "45", region: "Ouest", …}

Below is the code snippet where I call the XHR function and read the JSON:

var getDatas = getXHR(), // xhr in another file
    regions = {};
    dateRange = [];

getDatas.open("GET", "./db/datas.json", true);
getDatas.send();

getDatas.onreadystatechange = function() {
    if (getDatas.readyState === 4 && (getDatas.status === 200 || getDatas.status === 0)) {
        var robotsList = JSON.parse(getDatas.responseText);
        getRobotsDatas(robotsList);
    }
};

function getRobotsDatas(robotList) {
    for (var i = 0; i < robotList.length - 1; i++) {...}

The issue I'm facing is that the last object in the JSON data is never loaded... Can someone guide me on the correct approach to resolve this?

Thank you in advance!

Answer №1

Suppose that robotsList is actually an array of objects (which may not be entirely clear from the provided "json" code snippet).

You might want to review how you're iterating through the array within the getRobotsDatas function.

It seems like you're looping one time too few. Here's the current loop statement:

for (var i = 0; i < robotList.length - 1; i++)

This should either be modified to:

for (var i = 0; i < robotList.length; i++) // removed the - 1

or adjusted to:

for (var i = 0; i <= robotList.length - 1; i++) // changed < to <=

In my view, I find the first option to be more straightforward.

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

The data from the Flickr API is consistently unchanging

I created a simple weather app that retrieves weather data using a "POST" request and displays it successfully. Users have the ability to search for weather by city, and I wanted to enhance the app by loading an image of that city through a separate jQuer ...

Problem with unusual symbols

I am experiencing a problem where special characters are not displaying correctly on my website. To address this, I am executing an ajax query with a Python script on the backend : $.ajax({ ...

Javascript: A Fun Game of Questions and Answers

When using JavaScript exclusively, I have an array consisting of four questions, four correct answers, and four incorrect answers. The use of arrays is essential to maintain order in the data. As each question is displayed, a random number is generated by ...

Is there a way to display only the specific child div within the parent div using JavaScript without affecting the others?

   **** Sorry for the lengthy title **** Today I encountered a problem that I would like to discuss with all of you. When I click on a "COMMENT" button, instead of triggering JavaScript code to display a CHILD.div inside the corresponding ...

What is the best way to insert a button at the end of the last row in the first column and also at the

I am working on a JavaScript project that involves creating a table. My goal is to dynamically add buttons after the last row of the first column and also at the top of the last column. for (var i = 0; i < responseData.length; i++) { fo ...

What is the best way in jQuery to show each element of an array one at a time with a space in an input field?

I have a large array filled with strings that I want to display one by one in a text field, automatically concatenated with a space bar. Below is my code: <script> x = 0; function abc() { for (i = 0; i < words[x].length; i++) { ...

Obtain scope in AngularJS using object ID

Is it possible to retrieve the specific scope of an object by accessing it through an ID? I am currently using angular ui tree for a navigation menu. However, I face an issue where after adding a subitem and saving the navigation into a mysql database, th ...

Display validation in HTML5 only when the form is submitted

Here is the code snippet I am referring to: <input required pattern="[0-9]{5,10}" oninput="setCustomValidity('')" oninvalid="setCustomValidity('Type something')" /> I'm looking for a way to remove o ...

The property is returning an empty string, but the function is functioning perfectly

Check out this related Stack Overflow post exports.getAddress = asyncHandler(async (req, res, next) => { var lon = req.query.lon; var lat = req.query.lat; var formattedAddress = ""; var url1 = 'url' request(url1 ...

In JavaScript, navigate to a new page only after successfully transmitting data to the server

Creating a redirect page that sends data to the server before transitioning to a new page can be achieved using JavaScript as shown below. <body> <script type="text/javascript"> **** Discussion of cookie-related transactions **** document.c ...

How can I track the number of correct answers in a ReactJS quiz with an auto-submit feature and a timer that stops?

The auto-submit feature is not functioning correctly. Although the code works fine when I manually submit the quiz at the end, if the time runs out, the score will always be 0/3 which is incorrect. // React and Material-UI imports omitted for brevity // ...

structure nested json data in Golang and retrieve values

Struggling with parsing nested JSON into structs using Go language I have a complex JSON string that I need to parse using struct in Go language. The structure of the JSON is as follows: {"action":"add","business":{"List ...

Is there a way to create an <a> element so that clicking on it does not update the URL in the address bar?

Within my JSP, there is an anchor tag that looks like this: <a href="patient/tools.do?Id=<%=mp.get("FROM_RANGE") %>"> <%= mp.get("DESCRITPION") %></a>. Whenever I click on the anchor tag, the URL appears in the Address bar. How can ...

Dealing with incorrect routes found in both documents

In my current project, I am facing an issue where I need to handle invalid routes and display a message in Node.js. I have two separate files, one for users and one for tasks. If a user accesses a route that does not exist, I want to show an error message ...

Seeking the location of the `onconnect` event within the Express framework

With the use of "express," I have implemented a middleware function like so: app.use(function(request, response, next) { console.log(request.headers["user-agent"]); // etc. }); This currently displays the user-agent header in the console for ever ...

Tips for handling JSON response from REST request in Java without a root element name

The response I received after sending my request is as follows: [ { "data":{ "channel":{ "id":"708087644", "__typename":"User" } ...

How to use JQuery UI sortable to automatically scroll to the bottom of the page

Having trouble with a few sortable tables and here is how I initialized the sortable object: var options = { helper: customHelper, handle: ".moveTargetDeliverables", containment: "#fieldset_deliverables_summary", tolerance: 'pointer&a ...

Encountered an issue while attempting to include multiple JavaScript sources. Please review your configuration settings for the javascripts.join

While setting up a basic app using phoenix-elixir and brunch, encountering the following error: 23 Mar 10:18:10 - warn: node_modules/phoenix/priv/static/phoenix.js compiled, but not written. Check your javascripts.joinTo config 23 Mar 10:18:10 - war ...

Stop json_encode from converting empty strings to null values

Can the PHP function json_encode be configured to retain empty string values instead of converting them to null? UPDATE: After further investigation, it appears that the default behavior of the json_encode function already retains empty string values wi ...

Using jQuery and Bootstrap in an ASP.NET Core project

I am encountering an issue with the configuration of bootstrap and jquery within my project, causing these tools to fail to load properly. The problem seems to be that bootstrap is loading before jquery, resulting in error messages appearing when I check ...