Executing an http request within a nested loop in JavaScript

Within my angular application, I am faced with the challenge of working with two arrays structured as follows:

$scope.data = ["val 10,val 11,val 12", "val 20,val 21,val 22", "val 30,val 31,val 32"];

$scope.fields = [ "key1", "key2", "key3" ];

My task is to properly format and send each element of the $scope.data array to the server in the following manner:

{
  key1: 'val 10',
  key2: 'val 11',
  key2: 'val 12',
}
{
  key1: 'val 20',
  key2: 'val 21',
  key2: 'val 22',
}
{
  key1: 'val 30',
  key2: 'val 31',
  key2: 'val 32',
}  

However, a significant issue arises during this process; upon sending the data to the server, only the last value of $scope.data is being received. Reviewing my code below:

// $scope.data = ["val 10,val 11,val 12", "val 20,val 21,val 22", "val 30,val 31,val 32"];
_.each($scope.data, function(result, index) {

  var dataArray = result.split(","); 

  _.each(dataArray, function(info, position) {

    if( info !== null || info !== '' || info.length > 0 )  {
      $scope.data[ $scope.fields[position] ] = info;                                                         
    }
  });

  $http
    .post(url + '/import-data', {
      "data": $scope.data
    })
    .then(function (res) {
      console.log(res); 
    }, function (error) {
      console.log("error : ", error);
    })

});

I am seeking advice on resolving this dilemma. Appreciate any insight you can offer. Thank you.

Answer №1

Give this a shot:

Use the following code snippet:

_.forEach($scope.data, function(item, key) {

    var splitData = item.split(","); 

    $http
       .post(url + '/import-data', {
            "data": _.object( $scope.fields, splitData)
       })
      .then(function (response) {
          console.log(response); 
       }, function (err) {
          console.log("error : ", err);
       })

  });

Answer №2

I have set up a new variable known as $scope.serverdata for your convenience. Remember to transmit this data to the server.

$scope.data = ["val 10,val 11,val 12", "val 20,val 21,val 22", "val 30,val 31,val 32"];
$scope.fields = ["key1", "key2", "key3"];
$scope.serverdata = [];
angular.forEach($scope.data, function(result) {
    var dataArray = result.split(",");

    var value = {};
    angular.forEach($scope.fields, function(field, index) {
        if (value[field] == undefined) {
            value[field] = dataArray[index];
        };

    });
    $scope.serverdata.push(value);
});
});

The contents of $scope.serverdata now appear like this:

{
 key1: 'val 10',
 key2: 'val 11',
 key3: 'val 12',
}
{
 key1: 'val 20',
 key2: 'val 21',
 key3: 'val 22',
}
{
 key1: 'val 30',
 key2: 'val 31',
 key3: 'val 32',
}  

You can access the fiddle link here:

http://fiddle.jshell.net/LXAt7/655/

To make a request, use the following code:

$http
   .post(url + '/import-data', {
     "data": $scope.serverdata
   })
   .then(function (res) {
     console.log(res); 
   }, function (error) {
     console.log("error : ", error);
   })

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 is the best way to integrate React Portal with React Hook?

There is a specific requirement to listen to a custom event in the browser and then have a button that triggers the opening of a popup window. Currently, React Portal is being used to open this secondary window (PopupWindow). However, when hooks are used i ...

Display the status in the textbox once a dropdown value has been selected

I have a function that allows me to add shops. Within this function, I am able to select whether the shop is OPEN or CLOSED. The goal is for the status of the shop, either OPEN or CLOSED, to appear in a textbox on another modal. When creating a user and ...

Saving the image logo into local storage during page loading process in AngularJS

I am looking for a way to save an image logo to local storage when a page is loaded in my AngularJS application. angular.module('app', [ 'ngStorage' ]). controller('Ctrl', function( $scope, $localStorage ){ ...

Retrieve content from the pushState state object

$(function(){ $('button').click(function(e){ e.preventDefault(); var nextUrl = 'page1.html'; var previousUrl = window.location.href; $.get(nextUrl, function(data){ $('body').ht ...

Steps for updating the value of angular inputs within a function

When a card is selected on the page below, the input values should be updated with information from a JSON object. Here is the JSON data: { "status": true, "data": [ { "id": 1, "pessoa_id": 75505 ...

Developing a TypeScript library through modular class implementation

I have developed a Web API and now I want to streamline my code by creating a library that can be reused in any new project I create that interacts with this API. My goal is to organize my code efficiently, so I plan to have separate classes for each endp ...

Leverage the fs module in Node.js using npm packages, without the ability to use it

In the process of developing a library using Webpack that must be compatible with both browser and Node.js environments, I encountered an issue. There is a single function within the library that requires the use of 'fs', specifically for compati ...

The issue of Dynamoose/DynamoDB converting empty arrays to null during updates

Utilizing the Node.js package Dynamoose to manage DynamoDB requests within my web application has been a challenge. An issue arises when attempting to update an item that contains an empty array in the JSON object. It seems that Dynamoose is setting this ...

$filter is functioning correctly, however it is generating an error message stating: "Error: 10 $digest() iterations reached. Aborting!"

Here is an example of a JSON object that I am working with: { "conversations":[ { "_id": "55f1595d72b67ea90d008", "topic_id": 30, "topic": "First Conversation", "admin": "<a href="/cdn-cgi/l/e ...

Creating a VueJS computed property that dynamically responds to changes in the `window.innerWidth`

Essentially, I am searching for a computed property that will evaluate to true when the window.innerwidth is 768px or less and to false when it exceeds 768px. This is what I have attempted: computed: { isMobile() { if (window.innerWidth <= 768) ...

Remain on the current webpage following the submission of comparable ajax-forms

Seeking assistance with an issue involving Ajax that I believe is unique. Desired Outcome I have a newsfeed with various posts and interspersed forms, such as polls, for user interaction and submission of results. Objectives Users should be able to inter ...

Creating stylish error labels using Materialize CSS

While Materialize has built-in support for validating input fields like email, I am looking to implement real-time validation for password inputs as well. This would involve dynamically adding error or success labels using JavaScript. Unfortunately, my at ...

Problem with displaying information in the table based on the numerical input

How can I dynamically set the number of rows in a table based on an input field? var app = angular.module("myApp", []); app.controller("myCtrl", function($scope) { $scope.myObj =[ {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin ...

Populate select2 with the selected value from select1 without the need to refresh the page or click a button

Being a novice in PHP and Javascript, I am looking for a way to populate the "info" select dropdown based on the selected value from the "peoplesnames" dropdown without refreshing the page or using a button. Here's my code: HTML: <select id="peo ...

What could be the reason that setting document.body.style.backgroundImage does not apply to the body element itself?

Consider an HTML document with the given CSS: body { background: url("http://via.placeholder.com/200x200"); width: 200px; height: 200px; } Why does the following code not display the background image URL when executed: console.log(document.body. ...

Using a Component's Variable in Another Component in React Native

Hello there! Thank you so much for offering your help. I have a component called PlayerWidget and would like to utilize its state variable isPlaying value in the AlbumHeader Component. Here is the code for the PlayerWidget: import React, { useContext, use ...

React - the constructor binding issue with 'this' keyword

I am a beginner in React and I am learning through creating a simple test application. However, I am facing an issue with "this" binding. I set up this app package yesterday using "create-react-app", so all the necessary plugins including babel should be u ...

What is the best way to capture a GET request event?

I am having trouble with the following code snippet: $(window.document.location).change(function (){ }); Can someone advise me on how to determine the appropriate time to begin sending data back to the server? UPDATE: To clarify, I am specifically inte ...

What steps can a web developer take to view user console errors?

Is there an effective method for a web developer to receive notifications of console errors logged by other authorized users? I am currently working with Express, Passport, and MongoDB. These errors may occur on either the client or server side. One approa ...

Terser is causing ng build --prod to fail

When I run ng build --prod on my Angular 7 application (which includes a C# app on the BE), I encounter the following error: ERROR in scripts.db02b1660e4ae815041b.js from Terser Unexpected token: keyword (var) [scripts.db02b1660e4ae815041b.js:5,8] It see ...