JavaScript: experiencing difficulty incorporating API string into JSON format

When I am trying to add values to a JSON object manually, it works fine:

Code:

for (var k = 0; k < result.length; k++) {    
    result[k]["sender"] = k;    
}

https://i.sstatic.net/jnbpw.png

However, when I fetch values from an API and attempt to store them in result[k]["sender"] , the values are not being saved in the JSON object, and instead, they are being printed on the console:

for (var k = 0; k < result.length; k++) {
    var url = "//api";

    $.ajax({
        url: "https://reverse.geocoder.api.here.com/6.2/reversegeocode.json?prox="+result[k]['lat'].toString()+","+result[k]['lon']+"&mode=retrieveAddresses&app_id=***&app_code=***",
        context: document.body,
        success: function (data) {
            console.log(k, typeof data['Response']['View'][0]['Result'][0]['Location']['Address']['Label']);
            result[k]["sender"] = data['Response']['View'][0]['Result'][0]['Location']['Address']['Label'];
        }
    });
}

Error: https://i.sstatic.net/cpoAt.png

Could someone provide guidance on what might be causing this issue?

Answer №1

Replace var k with let k.

k is incremented during each loop iteration, reaching a final value of result.length when the loop ends.

Initially, your loop runs for result.length iterations, incrementing k each time, and initiates several requests using $.ajax. These requests are asynchronous, meaning their completion and the triggering of the success function occur later, while the rest of the code continues executing.

Subsequently, as the requests finish, they try to access result[k]. However, at that point, k === result.length because the loop has finished, resulting in result[k] being undefined.

By using let, you take advantage of a special feature in ES6 where a let variable within a for loop creates two instances of the variable; one for counting and the other for retaining the value within the loop's closure. This ensures that each iteration of the loop maintains its own k value even after progressing through the loop.

Note: If your url is not static and depends on k at any point, it should also be declared with let to prevent the same issue.


Alternatively, if ES6 is not an option, you can create a new scope using an Immediately-Invoked Function Expression (IIFE) and pass the variable as an argument:

for (var k = 0; k < result.length; k++) {
  (function (k) {
    // Perform $.ajax and other tasks here
  })(k);
}

Alternatively, you could utilize forEach which automatically provides a new variable for each callback execution.

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

Swap out ASP.NET AJAX with jQuery for making ASHX requests

Recently, I have been utilizing the following method to communicate with a Web Proxy for cross domain calls. However, as I am in the process of updating my code and already use jQuery, I am considering dropping ASP AJAX since it is only used for this speci ...

Populating a clickable list and form with a complex JavaScript object

I have a code snippet that takes an unstructured String and parses it into a JavaScript object. My next step is to integrate it into a web form. You can check out the demo here. The demo displays the structured object hierarchy and showcases an example of ...

Storing data with NPM global packages: Best practices

I have developed a global npm package that functions as a CLI tool. https://i.sstatic.net/PdT3Z.png My goal is to customize the user experience by having the package remember the user's previous choices. For example, if the user selects 'Iphone ...

Skip nodes in Polymer 1.0 by using ExcludeLocalNames

I recently attempted to transition from Polymer version 0.5 to 1.0 and came across a particular question: Is there a way to exclude certain nodes inside a paper-menu? In the previous version (0.5), you could use the attribute excludedLocalNames to achieve ...

Exporting Javascript functions is not possible

Programming in TypeScript import { Component, OnInit } from '@angular/core'; import {loadCalendar} from '../../../../scripts/artist/artist-home'; import {activate_searchBar} from '../../../../scripts/search_bar_activate'; @C ...

changing the name of a variable within ng-include

Here is some important HTML code: <ng-include src="'app/views/order.html'"></ng-include> Within the scope of this ng-include, there is a variable called trade. The structure of the trade variable is as follows: var trade = { or ...

I'm wondering if you have any insights on how to retrieve objects using Mono WebAssembly

I am looking to send a c# object back via mono-wasm, but when I attempt to do so, the returned object appears in my JavaScript file here. The C# code can be found in [image2]: C# code My JavaScript code can be found here: JS code Everything seems to wor ...

The integration of VueJS with the Canva Button JS API amplifies the

I have been exploring Canva's Button JS API which can be found at My goal is to implement a modular approach in utilizing their API, only loading the CanvaJS when necessary. My implementation involves triggering the load function when a button is cli ...

Automatically updating a database value in CodeIgniter after a countdown has expired

I am looking to automatically update a value in my MySQL database using CodeIgniter once a countdown timer reaches zero. However, I am struggling to figure out how to implement this. Here is an example: I have a database structured like this: [image lin ...

JavaScript - Modify the proposed content prior to inserting it into the input field

In my current project, I have implemented a feature using jQuery UI - v1.11.4, where an HTML textbox utilizes a JavaScript autocomplete functionality. The suggested string for the textbox is created by concatenating several columns (patient_no, patient_nam ...

Mocha: A Unique Perspective on Testing the express.Router Instance

As I was developing a JavaScript controller file, I came across the need to test if my controller instance contains an instance of the express method called Router(). import {assert} from 'chai'; import {UF_Controller} from '../../controlle ...

Resetting the selected options in AngularJS dropdown lists

Utilizing ng-repeat in my HTML code to iterate over a JavaScript array and displaying it within a selection. I am trying to achieve the functionality of clearing all selected data from these dropdown lists when a button is clicked. Snippet of HTML: <d ...

The state in Reactjs is not displaying as expected

Check out my ReactJS todo app that I created. However, I am facing an issue with deleting todos. Currently, it always deletes the last todo item instead of the one I click on. For example, when trying to remove 'Buy socks', it actually deletes ...

What is the best way to store a username and password within a JavaScript object in ReactJS?

I am encountering an issue with obtaining the login credentials from the object. Although the code snippet below functions perfectly well with other forms. SignIn.js export default function SignIn(props) { const [state, setState] = useState({ userna ...

Initialization of Arrays with Default Values

I have taken on the task of converting a C++ program into JavaScript. In C++, when creating a dynamic array of type float/double, the entries are automatically initialized to 0.0; there is no need for explicit initialization. For example, a 1-D vector of ...

How do I retrieve the HSL value for a color selected using an input of type 'color' in JavaScript?

I am faced with a creativity block and don't know where to begin. My goal is to develop functions that can manipulate the HSL values once I have access to them. Specifically, I am interested in modifying the light value, which is why I require it in ...

The functionality of the date picker is hindered when a dropdown with multiple selections is activated, and conversely, the multi-selection feature of

I am working on an application where I need to implement a drop-down with multi-selection functionality, as well as a date picker for text boxes. For the drop-down with multi-selection feature, I referred to the code in the following link: . Additionally, ...

What is causing the onclick event to not function properly when called from an external .js file?

I've created a .js file that contains code for a photo album application. The file includes functions for changing images when buttons are clicked. However, when I interact with the buttons, the images do not change as expected. The code in the .js f ...

Can JavaScript be used to dynamically update drop down lists in a gridview?

My gridview has multiple fields including PreviousPoints, GainedPoints, and TotalPoints. In edit mode, PreviousPoints is not editable, GainedPoints is a dropdown list, and TotalPoints is also a dropdown list. Whenever the selected value in GainedPoints ch ...

The NPM version needs to be updated as it is outdated

Struggling with a dilemma here. My Laravel project is quite dated, and I'm unable to execute npm run dev. Let's take a look at some code: php artisan laravel --version: Laravel Framework 5.8.38 node --version: v16.16.0 This is the current Node v ...