Steps for iterating through array objects within a function

I am encountering an issue with vs.selectedTags array, which consists of 3 objects.

Within a for loop that iterates 3 times, I need to make 3 API calls to retrieve ticker data for each object, a task I have successfully accomplished.

The problem arises when I attempt to assign these tickers to the vs.selectedTags[i].tickers object in the array.

The issue lies in the inability to iterate over the i within the ApiFactory call. As i reaches a value of 3, I have resorted to using [i-1] to prevent errors. However, despite this workaround, i remains at a value of 2, resulting in the last tickers' data being saved for all items in the vs.selectedTags array.

var vs = $scope;

for (var i = 0; i < vs.selectedTags.length; i++) {

    console.log(i);

    vs.selectedTags[i].tickers = '';

    console.log(vs.selectedTags[i].tickers);

    ApiFactory.getTagData(vs.chosenTicker, vs.selectedTags[i].term_id).then(function(data) {

        // console.log(data.data.ticker_tag);
        console.log(data.data.ticker_tag.tickers);

        console.log(i-1);

        // console.log(vs.selectedTags[0]);

        // How would you properly iterate [0 - 1 - 2] here?
        vs.selectedTags[i-1].tickers = data.data.ticker_tag.tickers;

        console.log(vs.selectedTags[i-1]);
    });
}

Answer №1

To handle the asynchronous nature of the ApiFactory.getTagData function, create a closure or new scope:

for (var i = 0; i < vs.selectedTags.length; i++) {
    (function(j) {

        vs.selectedTags[j].tickers = '';

        ApiFactory.getTagData(vs.chosenTicker, vs.selectedTags[j].term_id).then(function(data) {

             vs.selectedTags[j].tickers = data.data.ticker_tag.tickers;
        });
    })(i);
}

Answer №2

To resolve the closure issue, you can solve it by placing the contents of your for loop inside a separate function like this:

var processData = function(index){
    console.log(index);

    vs.selectedTags[index].tickers = '';

    console.log(vs.selectedTags[index].tickers);

    ApiFactory.getTagData(vs.chosenTicker, vs.selectedTags[index].term_id).then(function(data) {

        // console.log(data.data.ticker_tag);
        console.log(data.data.ticker_tag.tickers);

        console.log(index);

        // console.log(vs.selectedTags[0]);

        // How would you properly iterate [0 - 1 - 2] here?
        vs.selectedTags[index].tickers = data.data.ticker_tag.tickers;

        console.log(vs.selectedTags[index]);
    });
}

for (var index = 0; index < vs.selectedTags.length; index++) {
    processData(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

Enlarge image when clicked

I need help creating a gallery page where users can click on an image to enlarge it, then navigate through the images using arrows on either side. I am not familiar with JavaScript, so could someone guide me on how to achieve this? Also, I would apprecia ...

Tips on how to display a gif image during the loading of ajax content using JavaScript

Currently, I am attempting to load a gif image while waiting for the AJAX data to be loaded and displayed. However, I am struggling with this task. I would appreciate any assistance on how to implement a loading gif in my code for the advanced search feat ...

Is my HTML <h1> text not updating properly? I'm wondering if I linked app.js correctly

I'm currently learning the basics on a new machine and facing an issue where I am unable to modify the text within the header. It appears that the app.js file might not be properly connected to my index.html file. Within the app.js file, I have the f ...

Mastering socket emission and disconnection in reactjs

When using the onchange function, I am able to open a socket and emit/fetch data successfully. However, a new socket is opened on any event. I need to find a way to emit data from the same socket ID without opening a new socket each time. Could you pleas ...

Removing specific row values from an array within a table

Attempting to generate an array from chosen table rows in order to push it to a new view. Encountering an issue when attempting to delete an unselected row from the array, which results in an error of index beyond bounds, despite having other items selecte ...

When the mouse button is released or when an event listener is

I've been pondering a question that has yet to be fully answered. When I implement this technique to catch a mouse up event: <div onmouseup="/*Script to be executed*/"></div> Is it more efficient than this newer approach: <div id=" ...

Tips for personalizing a drop-down menu in AngularJS with the Ionic framework

Being new to AngularJs and the Ionic framework, I am currently working on building a dropdown list component. I have successfully created one using the code below. Here is the HTML structure: <ion-view title="Drop down list"> <ion-content& ...

Can Angular Directives be declared solely in HTML code?

(Linked to my previous question on Programmers.SE: ) It becomes cumbersome to write JavaScript boilerplate in a separate file just to create a Directive when wanting to reuse a few lines of HTML. I wish there was a way to define a Directive directly withi ...

Encountering an issue with Angular virtual scrolling: ViewDestroyedError arises when trying to utilize a destroyed view during detectChanges operation

My implementation involves using virtual scrolling from the cdk within a trigger-opening sidenav on a mat-radio element. Here is the code snippet: ts - ... @Component({ selector: 'app-generic-options-list', templateUrl: './generic-opt ...

Guide to dynamically resizing the Monaco editor component using react-monaco-editor

Currently, I am integrating the react-monaco-editor library into a react application for viewing documents. The code snippet below showcases how I have set specific dimensions for height and width: import MonacoEditor from 'react-monaco-editor'; ...

Can jQuery be used to change the functionality of a submit button, such as toggling between show, hide, and submit options?

I am having trouble toggling a button to either submit a form on click or reveal an input field, depending on whether the user clicks outside the input field to hide/collapse it. The issue arises when the user dismisses the input field and the submit butto ...

Error encountered: "XPathEvaluator is not defined" when using IEDriverServer and Internet Explorer with Selenium and Java in Microsoft Dynamics CRM

As part of my testing process for a CRM application with Selenium Java, I encountered an issue with a button that opens a new window. When executing the test, a Script Log Error appears in the new window stating, ReferenceError: 'XPathEvaluator&apo ...

Send the form via ajax

I am in the process of creating a unique application for my university, which is essentially a social network. One key feature I need to implement is the ability for users to add comments, which involves inserting a row into a specific database. To achieve ...

Converting JSON Data to Map Markers on Google Maps

Currently, I am attempting to pass a Json String into my Javascript code in order to create a list of markers on a Google Map. The map code functions properly as I have successfully tested it with a hard coded Json Object. However, now I need to fetch the ...

``What is the mechanism behind callbacks in AngularJS when making a call to a REST service?

Currently, I am diving into the world of AngularJS and REST. The code snippet that I'm analyzing has the term callback repeatedly used in an authentication function. I'm curious to know if "callback" is a JavaScript or Angular keyword, or simply ...

Combining multiple arrays of arrays in JavaScript

I am dealing with an array that contains nested arrays. This particular array is called template https://i.sstatic.net/QIs0Q.png template consists of 2 arrays, but the number can vary and there can be multiple levels of arrays within each one. Here' ...

Transferring canvas element via socket with JS stack size limit

I'm encountering an issue where I need to transfer a canvas element over sockets using socket.io and Node.js. The code snippet below illustrates my approach: var myCanvas = document.getElementById("myCanvas"); var ctx = myCanvas.getContext("2d"); // ...

In Angular code, the foreach loop jumps to the next function before completing each iteration of the loop

private processArray(evts: Event[]): Promise<void> { var auditsvc = this.auditSvc; var t = this; if (!evts || evts.length == 0) { return; } let objArr: any[] = []; evts.forEach(function (inpEvt) { auditsvc.getAuditDetails(inpEv ...

Display or conceal component based on specific URL in React.js navigation bar

Hey there, I'm facing an issue with hiding certain links in the navbar when users visit specific pages. For instance, on the Landing page, I want to hide the Orders and Basket links and only show the Login link. I'm having trouble figuring out ho ...

Ending an $.ajax request when the page is exited

Currently, I have a function set on a timer to retrieve data in the background: (function fetchSubPage() { setTimeout(function() { if (count++ < pagelist.length) { loadSubPage(pagelist[count]); fetchSubPage(); ...