Combining multiple JSON objects into a single array in AngularJS

Currently, I am facing a challenge in merging two API calls. The first call involves fetching data by filtering the account_id on the backend, while the second call retrieves data based on the test_id.

Let's start with the JSON response for /api/test-overview:

{
    testSprint: [
        {
            account_id: 27,
            test_id: 3,
            name: "Junior"
        },
        {
            account_id: 27,
            test_id: 50,
            name: "Wilson"
        }
    ]
}

When the test_id is 3, the JSON structure for activityAvgService looks like this:

{
    test_id: "3",
    stats: {
        avgE: 2.5,
        avgD: 43.3,
        avgA: 5.7,
        avgH: 6.3,
        highH: 0
    }
}

Similarly, when the test_id is 50, the JSON response is as follows:

{
    test_id: "50",
    stats: {
        avgE: 1,
        avgD: 33,
        avgA: 3,
        avgH: 1,
        highH: 0
    }
}

In my controller, I have implemented a $http request to fetch the initial /api/test-overview data. Following are the essential steps:

$http.get("/api/test-overview").then(testResponse => {
    $scope.test = testResponse.data.testSprint;
    for (var i = 0; i < $scope.test.length; i++) {
        activityAvgService.showStatsAVG($scope.test[i].test_id).then(response => {

            var stats = response.data.stats

            console.log("stats", stats);
        });
    }
});

The ultimate goal here is to merge all three JSON responses into the original /api/test-overview JSON. Ideally, the combined JSON should look like this:

{
    testSprint: [
        {
            account_id: 27,
            test_id: 3,
            name: "Junior",
            stats: {
                avgE: 2.5,
                avgD: 43.3,
                avgA: 5.7,
                avgH: 6.3,
                highH: 0
            }
        },
        {
            account_id: 27,
            test_id: 50,
            name: "Wilson",
            test_id: "50",
            stats: {
                avgE: 1,
                avgD: 33,
                avgA: 3,
                avgH: 1,
                highH: 0
            }
        }
    ]
}

I have attempted using map and concat methods but without success. Any fresh ideas or insights on how to proceed would be greatly appreciated!

Thank you in advance for your assistance!

Answer №1

Make sure to lock the index value i when performing the internal ajax call.

Here is a suggested approach:

$http.get("/api/test-overview").then(testResponse => {
      $scope.test = testResponse.data.testSprint;
      for (var i = 0; i < $scope.test.length; i++) {
        (function(test, i) {
          activityAvgService.showStatsAVG(test[i].test_id).then(response => {
            var stats = test[i].stats; // this will be reflected in the outer test array
            console.log(test, stats);
          });
        })($scope.test, i)
      }
    }

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 split an array into smaller chunks?

My JavaScript program fetches this array via ajax every second, but the response time for each request is around 3 to 4 seconds. To address this delay, I attempted to split the array into chunks, however, encountered difficulties in completing the task: { ...

Error encountered: The module '@mui/x-data-grid' does not export 'GridActionsCellItem'

I'm facing an issue while trying to import 'GridActionsCellItem' from '@mui/x-data-grid'. Here's the code: import { GridActionsCellItem } from '@mui/x-data-grid'; An error message pops up indicating: Attempted impor ...

What are the advantages of using Yarn instead of NPM? Understanding the distinctions between the two package managers

What sets Yarn apart from NPM? I've been scouring the internet for articles that compare Yarn and NPM, but all I find are resources detailing the equivalent commands between the two. While both seem to offer similar functionalities, such as local cac ...

In order to enable automatic playback of background images

Having created a slider with hover functionality on icons to change background images, I now seek to add an autoplay feature to the slider. The slider was implemented in a WordPress project using Elementor and involved custom Slider creation through JavaSc ...

tsconfig.json respects the baseUrl for absolute imports inconsistently

While using create-react-app, I have noticed that absolute imports work in some files but not in others. Directory Layout . +-- tsconfig.js +-- package.json +-- src | +-- components | | +-- ui | | | +-- Button | | | | +-- Button.tsx | ...

The browser prevented the script located at “http://127.0.0.1:5500/assets/platform.png” from loading due to an invalid MIME type of “image/png”

Sorry if this question seems repetitive, but despite extensive searching, I haven't been able to find a solution to my specific problem. I am currently working on developing a basic JavaScript game, but I'm facing challenges when it comes to impo ...

How is it possible that my code is continuing to run when it is supposed to be

My API has a limitation of 50 requests per minute for any endpoint. In the code snippet below, I filter objects called orders based on their URLs and store the ones that return data in successfulResponses within my app.component.ts. Promise.all( orders.ma ...

Is there a way to use jQuery to hide rows in a data table that contain a specific code, such as "1.1" or "1.2," that includes a

When using ajax, I pass data from two inputs to another page. These values are then used in a query to display the results in a data table on the main page within the success function. Now, I'm looking to implement a condition where any data containi ...

The ngModel feature is not functioning properly within the custom directive

After realizing my lack of understanding in AngularJs, I admitted that it was a challenge for me. Seeking clarity, I decided to post an example here and hope for assistance from someone knowledgeable on the topic. Thank you in advance. Html Part <test ...

Space between flex content and border increases on hover and focus effects

My code can be found at this link: https://jsfiddle.net/walshgiarrusso/dmp4c5f3/5/ Code Snippet in HTML <body onload="resize(); resizeEnd();"> <div style="margin: 0% 13.85%; width 72.3%; border-bottom:1px solid gray;"><spanstyle="visibilit ...

How do I save the value of a callback function in Vue data?

#I am facing an issue where the value of this.zuobiao is not being logged after I call the function that assigns a value to it. Why is this happening? getUserProfile() { uni.getLocation({ type: 'gcj02 ', geocode: true, success: (res) => ...

Invoking a function within an HTML file does not result in triggering an alert message

Hello everyone, thank you for taking the time to look at this. I'm attempting to execute a javascript function when I click on the update button. Here is the javascript code: var text2Array = function() { // This function takes the value from the t ...

Having trouble with the @keyup event not functioning properly in Vue?

I'm attempting to trigger a method when the enter key is pressed, but for some reason it's not working. Here's the code snippet: <template> <div> <button @click="callEvent" @keyup.enter="callEvent"> Click </button ...

Complex data in JSON format

Hello there, here is a snippet of JSON data: { "fields": [ "logoFileName", "logoFileName1", "companyEventIDUnique", "Date", "Event", "soldOut", "companyEventGroupDescription", "eventImage ...

What methods can be used to save mouse coordinates to a remote server?

As a beginner in server-side programming, I have some questions regarding my project built in JavaScript and Node.js. The current functionality involves sending mouse coordinates to the server and redrawing them on every client's screen. However, new ...

Transfer sound data blob to server and store it as a file

Currently, I have 3 buttons on my webpage - one to start recording audio, one to stop the recording, and one to play the recorded audio. Using MediaRecorder makes it easy to capture audio as a blob data. However, I am facing issues when trying to upload th ...

The X axis labels are missing on the Google column chart

Problem: All column charts are rendering correctly in Internet Explorer. However, Upon clicking the "View Build Performances" button, project names are displayed on the x-axis of the first three column charts only. The other column charts do not show pro ...

Learn how to efficiently pre-load data using the prefetchQuery method in React-Query

Attempting to pre-fetch data using react-query with prefetchQuery. The network tab in browser DevTools shows the requested data coming from the back-end, but strangely, the data is not present in the react-query DevTools cache. Any ideas on what might be c ...

Having difficulties retrieving the <td> id using jQuery

I am a beginner in the world of JavaScript and jQuery, and I am currently attempting to extract both the ID and the value of an element. Here is my initial AJAX request: $.ajax({ type: "POST", url: "Home/AddText", data: JSON.stringify({ te ...

What is the best way to connect multiple web pages together?

Hello everyone, I could really use some assistance with a problem I'm facing. As a newcomer to web development, I have a question about navigation bars. I've successfully created a basic webpage with a navigation bar, but now I'm unsure how ...