Traversing an array and connecting each element to a separate array in AngularJS

In my programming task, I am working with an object and an array that are defined as follows:

      $scope.multipleTransferGotten = [];

      $scope.newParameters = {
        UserId: "",
        Udid:"",
        TransType: "",
        SourceAccNumber: "",
        SourceAccName:"",
        BeneficiaryAccName: "",
        BeneficiaryAccNumber: "",
        Amount: "",
        Remarks: "",
        DestBankCode:"",
        AuthToken:"",
        UseToken: ""
      };

There is a specific line of code in my script that retrieves an array from the session storage;

 $scope.pickedTransfers = bank.getPaymentList($scope.paymentList);

What I need to achieve is to iterate through each element of the array obtained from the session and assign its values to $scope.newParamaters before pushing them into the $scope.multipleTransferGotten array. Here's how it looks like:

for (var i = 0; i < $scope.pickedTransfers.length; i++)
{
    $scope.newParameters.UserId = bank.getUserId();
    $scope.newParameters.Udid = bank.getUuid();
    $scope.newParameters.TransType = $scope.pickedTransfers[i].TransType;
    $scope.newParameters.SourceAccNumber = $scope.pickedTransfers[i].SourceAccNumber;
    $scope.newParameters.SourceAccName = bank.getAccountInfo()[i].CUSNAME;
    $scope.newParameters.BeneficiaryAccName = $scope.pickedTransfers[i].BeneficiaryAccName;
    $scope.newParameters.BeneficiaryAccNumber = $scope.pickedTransfers[i].BeneficiaryAccNumber;
    $scope.newParameters.Amount = $scope.pickedTransfers[i].Amount;
    $scope.newParameters.Remarks = $scope.pickedTransfers[i].Remarks;
    $scope.newParameters.DestBankCode = $scope.pickedTransfers[i].DestBankCode;
    $scope.newParameters.AuthToken = $localStorage.AuthToken;
    $scope.newParameters.UseToken = bank.getUseToken();

    $scope.multipleTransferGotten.push($scope.newParameters);
}

However, I'm encountering an issue where only the last index in the array populates the $scope.multipleTransferGotten array. Essentially, if I loop through 2 arrays, only the data from $scope.pickedTransfers[1] is stored twice in $scope.multipleTransferGotten.

I seek assistance in resolving this issue so that both $scope.pickedTransfers[0] and $scope.pickedTransfers[1] can be properly read, assigned, and stored in the $scope.multipleTransferGotten array. Thank you for your help.

Answer №1

To avoid getting the same values for all entries due to the same object reference, make sure to create a new empty object with no properties. Then, add all the desired properties to this object before pushing it to the array.

It is recommended to use a temporary variable that is not part of the $scope object.

var tempObject;
for (var i = 0; i < $scope.pickedTransfers.length; i++) {
    tempObject = {};
    tempObject.UserId = bank.getUserId();
    // ...

    $scope.multipleTransferGotten.push(tempObject);
}

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

What causes images to be omitted from a PDF file when using mywindow.print()?

Here is the scenario I am dealing with: On a particular webpage, there is a print button. The page contains various information, including receipts. When the user clicks on "print", I want only the receipts to be printed: https://i.sstatic.net/WobKK.png ...

Expanding a JavaScript list using HTML inputs

I have a script where a grid dynamically displays a list of words. Is there a way to populate the word list in the grid using HTML? Currently, I am doing this... var listOfWords = ["mat", "cat", "dog", "pit", "pot", "fog"]; Can additional words be adde ...

Inject CSS into an iframe containing a JavaScript form by iterating over a collection of iframes

My task is to manipulate an iframe (chatbox) once it's loaded on a webpage. This chatbox consists of four iframes, each with a different id that changes with every page load. Since the iframe that needs manipulation is always the last one in the list, ...

How can you run a function in JavaScript or TypeScript that is stored as a string?

Is there a way to call a function that is stored as a string? For example: var dynamicFun = `function Hello(person) { return 'Hello' + person; }` In this case, the dynamicFun variable can store any function definition dynamically, such as: var ...

Is there a way to utilize and incorporate Functions from a separate file within an API Server file?

I have integrated ReactJS, Firebase, and React Redux into my project. https://github.com/oguzdelioglu/reactPress Currently, I am displaying data from Firestore by utilizing Functions in https://github.com/oguzdelioglu/reactPress/blob/master/src/services/ ...

Express server experiencing issues with generating Swagger documentation

I've been working on an Express API and decided to implement documentation using Swagger and JSDoc. However, the documentation is not working as expected. Here's how I've set it up: docs.ts: import swaggerJSDoc, { Options } from "swagg ...

Managing Server Crashes in Node.js

Is there a way to automatically update the database whenever my node.js server crashes or stops? Similar to how try{}catch(){}finally(){} works in JAVA. I am new to this. Does Node emit any events before shutting down so that I can run my function then? ...

How to Insert <ul></ul> After Every Other <li> Element Using Angular's ngRepeat

With my current setup, I have a list item (li) within a list (ul) and applied ngRepeart. However, I would like to create a new ul after every 2nd li. Is this possible with AngularJS? <ul> <li>simth</li> <li>aryan</li> < ...

Unable to change the visibility of blockquotes using jquery

Currently, I am delving into the world of basic JQuery functions. My main focus right now is figuring out how to display the active blockquote while keeping the others closed or closing them. Essentially, creating a toggle effect where only one blockquote ...

What are the techniques used to minimize JavaScript functions?

Is there a more efficient way to reduce the amount of JavaScript code needed for functions that share the same call procedure? I'm struggling to find a clear explanation but here's the code snippet below... JavaScript: $(function() { $( &a ...

What is the best way to locate all mesh faces that are being lit up by a SpotLight

I am working with a THREE.Mesh that consists of a THREE.BufferGeometry containing "position" and "normal" THREE.BufferAttributes. This mesh is being lit by a THREE.SpotLight (which is a cone-shaped light source). Is there a method to ...

Retrieving results from PostgreSQL database using pagination technique

When I'm pagination querying my data from a PostgreSQL database, each request involves fetching the data in this manner: let lastNArticles: Article[] = await Article.findAll({ limit: +req.body.count * +req.body.page, or ...

Unable to utilize the resolved value received from a promise and returned from it

Within the code snippet below, I am retrieving a Table object from mysql/xdevapi. The getSchema() and getTable() methods return objects instead of promises. The purpose of this function is to return a fulfilled Table object that can be used synchronously i ...

Mastering the Art of Scrolling Down Content with Button Click in Ionic 3

I'm currently developing an Ionic chat application and I need the content to automatically scroll down when the user clicks on the send text button. You can see a visual representation of this in the images linked below. https://i.stack.imgur.com/gwR ...

Retrieving information from an AJAX callback

Is there a way to extract the URLs from PHP data? Here is an example script that may help you achieve this: PHP $query = 'SELECT * FROM picture LIMIT 3'; $result = mysql_query($query); while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) { ...

Having trouble with getting v-cloak to function properly when dealing with asynchronous requests

I wanted to explore using the v-cloak directive to showcase a loading spinner while certain data properties in vue js are being loaded asynchronously for me to integrate into a table component. After successfully applying and styling my v-cloak styles on ...

`Easily handle a Restangular resource``

I'm struggling with using Restangular for the first time and I'm having trouble understanding how to handle promises within my own service. I've attempted to use the customGET method but in my controller, the response is an object containing ...

The persistence of postback from the javascript function despite returning false when utilizing Asp Radiobuttonlist

HTML: <asp:RadioButtonList ID="rdStatus" runat="server" Height="48px" RepeatDirection="Horizontal" AutoPostBack="true" OnSelectedIndexChanged="rdStatus_SelectedIndexChanged" CssClass="rad"> ...

The like button animation works perfectly for individual posts, but for multiple posts, only the like button on the first post

Having an issue with the like button code on a single news feed. The button works for the first post, but when clicking on other posts, it only affects the first post button. I am using post UI and looping the UI based on the total post count without Javas ...

The slideshow fails to show correctly after being loaded from an external JavaScript file

Utilizing standard code, I have set up a Slideshow at the top of a website: HTML: <body id="Top" onload="showSlides()"> ... <div id="slides"> <div id="slide1" class="slides fade"></div> <div id="s ...