Combining AngularJS objects from dual HTTP requests

My goal is to combine two HTTP.get requests into one $scope in order to display the data in the same ng-repeat table. I am utilizing chained promises in my AngularJS application as shown below:

AngularJS:

function getContainer() {
            $http.get("/api/containers")
                .then(function (response) {
                    $scope.GTMcontainersAccount = response.data;
                    $scope.loading = false;


                    // Retrieve containerId and AccountID then send a request to show Counts of how many Tags, Triggers, and Variables are available in each Container
                    angular.forEach($scope.GTMcontainersAccount, function (key) {
                        angular.forEach(key, function (keydata) {
                            $scope.accountId = keydata.accountId;
                            $scope.containerId = keydata.containerId;
                            $http.get("/api/tags", {
                                params: {
                                    "param1": $scope.accountId,
                                    "param2": $scope.containerId
                                }
                            }).then(function (responses) {
                                $scope.tags_counter = responses.data[""]['tags'];
                                $scope.trigger_counter = responses.data[""]['trigger'];
                                $scope.variable_counter = responses.data[""]['variable'];


                            })
                        })

                    })
                })
        }

Explanation of the code:
1) http.get(/api/containers) retrieves data in JSON-format
2) angular.forEach iterates through the keys
3) angular.forEach iterates through the values (since keys are dynamic, there are 2 angular.forEach loops)
4) http.get(/api/tags) sends some parameters and receives result data

5) The challenge here is that I want to use ng-repeat on $scope.GTMcontainersAccount but cannot directly merge it with $scope.tags_counter, $scope.trigger_counter, and $scope.variable_counter.

The data in $scope.GTMcontainersAccount:

{
    "Account2": [{
        "accountId": "1746756959",
        "containerId": "7454209",
    }, {
        "accountId": "1746756959",
        "containerId": "7519183",
    }],
    "Account 1": [{
        "accountId": "1766143525",
        "containerId": "7483653",
    }]
}

The data in $scope.tags_counter (trimmed for brevity):

{
    "0": {
        "accountId": "***",
        "containerId": "*****",
        "tag": [{...}],
        "trigger": [{...}],
        "variable": [{...}]
    },
    "": {                 
        "tags": 3,
        "trigger": 3,
        "variable": 3
    }
}

After merging, I expect $scope.GTMcontainersAccount to look like this:

{
    "Account2": [{
        "accountId": "1746756959",
        "containerId": "7454209",
    }, {
        "accountId": "1746756959",
        "containerId": "7519183",
    }],
    "Account 1": [{
        "accountId": "1766143525",
        "containerId": "7483653",
    }],
    "Counter" : {
        "tags": 3,
        "trigger": 3,
        "variable": 3
}

UPDATED: https://i.sstatic.net/go0yb.png

Answer №1

Here is a fiddle I prepared for you.

Although it may look messy, it functions well.

I trust this will be beneficial to you. :)

Merge Object

$scope.GTMcontainersAccount['Counter'] = Object.values($scope.tags_counter)[(Object.keys($scope.tags_counter).length-1)];

To provide further clarification,

(Object.keys($scope.tags_counter).length-1)

The above code snippet retrieves the last index of an object.

Object.keys($scope.tags_counter) displays all keys associated with $scope.tags_counter.

Furthermore,

Object.values($scope.tags_counter)[index]
showcases all values related to $scope.tags_counter,

making it simple to retrieve any value by knowing its index in the object.

UPDATE

Your image has left me perplexed.

Why does every line feature the same 'Counter' object?

I am unsure whether you are assigning the identical object from '$scope.tags_counter' to multiple objects or not.

If the key you seek always contains an empty string like "",

you can utilize $scope.tags_counter[""];.

Kindly review this alternate fiddle.

Alternatively, could you create a fiddle including all your objects?

.

.

UPDATE2

To better understand your intentions, I have recreated this fiddle.

Please examine this updated fiddle,

and if this still does not align with your objectives, kindly provide me with additional information.

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

Testing nested mocked functions can be achieved by setting up the necessary mocks

How can I create tests for mocked functions within a mocked function? My goal is to verify that my publish mocked function is called only once. jest.mock('amqplib', () => ({ connect: jest.fn(() => Promise.resolve({ createChannel: jes ...

Unable to change the value of Apexcharts components

Utilizing the Vue.js framework along with the Apexchart library, I have been able to create scatterplots for my data. By making use of Axios, I can successfully transmit my data and monitor it using console.log(). With the help of Apexcharts property updat ...

What is the best way to manage HTML code that is delivered through JSON data?

I am dealing with data from a JSON that is in HTML code format. I need to print it as HTML, but currently it is only printing as a string: "content": "More tests\u003cbr /\u003e\n\u003cbr /\u003e\n\u003cdiv class=&bso ...

Tips for obtaining the iframe #document with cheeriojs?

I've been struggling to scrape the anime videos page [jkanime], specifically with extracting the mp4 video formats embedded in an iframe #document. Despite trying to use cheerio for querying, I've only managed to retrieve src links from Facebook ...

Utilizing reference memory to enable communication between two controllers

Within my Angular application, I have implemented a service to facilitate communication between 2 controllers and allow them to share the input variable from the search box. I am using kickSearch.box to reference memory...obj.property. However, there seem ...

Traverse through an array within an Object instantiated from a Class instance by utilizing the fetch(PDO::FETCH_ASSOC

I have a class that includes a viewData() method to retrieve data from a database table. I am trying to return the data result array within the Class and iterate through the array in an Object. While I have successfully implemented this using fetchAll(), I ...

Getting started with React Native project

Just dipping my toes into the world of React Native and looking for recommendations on the best starter kit/generator to kickstart my projects. Tried out "create-react-native-app" already, but curious if there are any other generators or kits out there tha ...

Steps for assigning values to a JavaScript array using its indices

Question: Dynamically creating keys in javascript associative array Typically, we initialize an array like this: var ar = ['Hello', 'World']; To access its values, we use: alert(ar[0]); // Hello However, I am looking to assign ...

create a custom data type in RAML that includes an array of diverse objects

I am currently working with two distinct Datatypes (and potentially more may be added in the future): #%RAML 1.0 DataType type: object properties: sftp: type: object properties: directory: type: string example: /upload ...

Having trouble with setting up local notifications in React Native's scheduling feature?

I have integrated the react-native-push-notifications npm library into my application to enable notifications. However, I am facing an issue while trying to schedule notifications using PushNotification.localNotificationSchedule. The code snippet for this ...

Navigating Dynamically between tabs - A How-to Guide

I am working on a mat-tab Angular app where I need to dynamically generate links and transfer them to a navLinks object. Despite ensuring that the concatenation is correct, it seems like my approach is not working as expected. Here's a glimpse of what ...

Error: Unhandled promise rejection - The function get is not part of this.categoryMap

I am facing an issue with calling functions of the Map (get, set, keys, etc) within my function. The map I am working with is returned from a firebase query. Here's a snippet of my code: categoryMap = new Map<Number, String>(); //called onInit ...

Utilizing Firebase authentication and next-auth in Next.js - Authentication currently returns null

I'm creating a website with nextjs 13 (app router) and incorporating firebase. I've come across suggestions to combine next-auth and firebase auth for using firebase auth effectively. Accordingly, I have configured my firebase Here is the fireba ...

Tips on embedding a textField into a designated row within a table by clicking a button with the help of reactjs and material ui

I need assistance adding multiple text fields to a specific row within a table when a designated row's "add" button is clicked. Currently, I am able to add a text field when the button is clicked, but it adds the text field to every row in the table. ...

Utilizing an array of objects without specified indexes

I am currently taking a class on factory workers and another one on factory products. While that's all good, I now want to develop a program in main() that prompts the user to input information about either a worker or a new product in the factory, us ...

Unable to include a JavaScript file within another JavaScript file

Currently, I am working on a project where I am utilizing Django for the backend and HTML/CSS/JS for the frontend development. On a specific HTML page, I am including two JS files: dom_creator.js and console_page.js. My goal is to access the functionaliti ...

Unable to access the "target" property while transferring a value from child to parent component

Within my project, the student component is considered a child component of the main app component. Inside the template of the student component, there is an input element defined like so: <input type='text' #inputbox (keyup)='onkeyUp(i ...

Include a search button within the search box of the Custom Search Engine

Can anyone help me with adding a search button to my HTML code? I've tried implementing it, but when I try to search something on a website like YouTube, the results show up without displaying my search query. How can I fix this issue and what changes ...

Generate sets of elements from an array

Allow me to elaborate on this concept. I have an array of values, and I am curious if it is feasible to generate another array consisting of combinations of these values. For instance: Assuming I have the following array: array('ec','mp&ap ...

Unable to deserialize the current JSON array within C# programming language

Transitioning from VB.NET to C# and encountering difficulties with JSON deserialization. Currently facing an error while attempting to deserialize a JSON array: Unable to deserialize the current JSON array Below is the class I'm deserializing the ...