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

Tips for concealing a "PARTICULAR TAB BAR ITEM" on a bottom tab bar in @react-navigation/bottom-tabs

Check out this video displaying my current visible bottom tab items: Home, My Account, Cart, and Menu. Watch here I have additional bottom tab items like SettingsView that I want to render on the screen but keep them hidden from the bottom tab bar itself. ...

Comparing JSON objects in Jackson and GSON for consistent and predictable results

Interestingly, Jackson does not support stable JSON object comparison as mentioned in this GitHub gist. This raises the question of whether GSON provides a solution for stable comparison of JSON objects without requiring custom overrides or implementatio ...

Generating unique identifiers for ng-model in AngularJS

Issue - ng-model is not generating dynamically. I have dynamic input boxes and I am attempting to create ng-model dynamically like test[1], test[2], etc. However, when inspecting the form with Firebug, all input elements only show - test[shiftnumber]. HT ...

Sorting Json Data Using Vue

My experience with Vue.js led me to a challenge I can't quite figure out: how to filter specific data in a Json file. Let me provide more context: I have a Json file filled with various electronics products such as computers, mice, keyboards, etc. I w ...

Reach out to the property via phone if it is listed in the JSON

When receiving JSON data from the server, I come across two different structures: JSON 1: { [{ name : 'sample1', code:'sample code 1', data : { display :'test' } ...

Passing an object in an ajax call to a function: a comprehensive guide

@model IEnumerable<HitecPoint.BlackBox.Models.SMSReportModal> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"> </script> <script type="text/javascript"> var MyAppUrlSettin ...

Event cancellation received from IncomingMessage

I have a simple express server running on Node with versions 4.13.3 and 4.2.3, respectively. //initialization code app.put('/', function(req, res) { req.on('close', function() { console.log('closed'); }); req.on( ...

Using a React button to sort through an array

Hey there, I'm currently working on an app that filters a list based on user input. The idea is to click on buttons to exclude users with specific letters in their names. However, the code I have right now isn't functioning properly. Any assistan ...

What is the method for reaching a service in a different feature module?

Currently, I am utilizing Angular 2/4 and have organized my code into feature modules. For instance, I have a Building Module and a Client Module. https://i.stack.imgur.com/LvmkU.png The same structure applies to my Client Feature Module as well. Now, i ...

"Encountering an unidentified custom element in Vue 2 while exploring Vue libraries

In my Vue project, I have integrated libraries like FusionCharts and VueProgressBar. However, I encountered an error in my console: Unknown custom element: <vue-progress-bar> - did you register the component correctly? For recursive components, make ...

How to Override package.json Scripts in NPM

Is it possible to modify package.json scripts without changing the original file? I need to customize the memory allocation for a specific step, but altering the package.json will affect everyone. For example, our current script is: "script": { "dev": ...

a guide on expanding a submenu in a shiny dashboard sidebar without using automated functions

I am facing a challenge in manually expanding a submenu within a sidebar on shiny dashboard. The function updateTabItems does not seem to work with nested menus, only with normal menus. For example, when I click on 'Switch tab', it switches the ...

Calling Node Express request inside a GET route

I am currently utilizing nodejs as an intermediary layer between my public website and an internal server within our network. Through the use of express.js, I have created a basic REST api where the endpoint should trigger a request call to a webservice a ...

What is the reason for typescript's lack of a "function" type?

As a newcomer to TypeScript, I'm puzzled as to why I am unable to define an object like this: const obj: { property1: string property2: boolean property3: function } It seems that the only workaround is to use: const obj: { property1: strin ...

Trigger the Modal once the navigation step is completed

When navigating to a new page, I need to wait for the navigation process to complete in order for the modal template to be properly displayed on the destination page. public onOpenModal(item) { this.router.navigate([item.link]).then(() => { this. ...

Issues with AngularJS <a> tag hyperlinks not functioning as expected

After performing a search, I have an array of objects that needs to be displayed on the template using ng-repeat. The issue arises when constructing the URL for each item in the array – although the ng-href and href attributes are correct, clicking on th ...

What occurs when socket.io events are not properly handled?

Is socket.io ignoring or dropping messages? I am asking this because there is a client with multiple states, each having its own set of socket handlers. The server notifies the client of a state change and then sends messages specific to that state. Howeve ...

The masonry reorganization is behaving strangely

I've recently started using masonry for the first time and you can check it out here: Although I have managed to set it up, I am facing some issues with its positioning of boxes when dragging items in. For example, instead of placing a medium-sized ...

Ensure that this regular expression is able to accurately match all numbers, even those without decimal points

Seeking help to create a script that can extract the negative percentage value between two numbers. One of the numbers is dynamic and includes different currencies, decimals, etc., so I believe a regex is needed for this task. The current script works, but ...

Pass an array from JavaScript to PHP

I am attempting to send an array to the server using jQuery. Here is my code snippet for sending the array: jQuery(document).ready(function($){ $.ajax({ type: "POST", url: "file.php", datatype : "json", data : JSON.str ...