Summing numbers with multiple queries in Angular services

One of my APIs/projects returns a JSON dataset like this:

[  
   {  
      "id":100,
      "name":"some name",
      "x": "y"
   },
   {  
      "id":200,
      "another name",
      "x": "z"
   }
]

Another API/costs call returns a similar dataset:

[  
   {  
      "projectid":100,
      "cost":300
   },
   {  
      "projectid":100,
      "cost":100
   },
   {  
      "projectid":200,
      "cost":500
   }
]

I initially wrote a messy code using ajax/jquery/JS to create a JavaScript object with "id", "name", and the total "cost". I then converted it into a JSON object.

As the queries became more complex, I found it inefficient and almost impossible to handle with raw JS. So, I decided to switch to Angular services, as they are easier to integrate for the front-end team.

Although I have little experience with Angular, I have created a simple service to query all projects or a single project based on its ID.

My question is, can Angular be used to query the APIs and generate a JSON that includes only the name and id from the first query, and calculates the total cost for each project from the second query? The desired output should be:

[  
   {  
      "id":100,
      "name":"some name",
      "cost":400
   }
]
[  
   {  
      "id":200,
      "name":"another name",
      "cost":200
   }
]

Thanks!

Answer №1

Here is a straightforward solution using plain Javascript and boasting linear complexity.

var projects = [{ "id": 100, "name": "some name", "x": "y" }, { "id": 200, name: "another name", "x": "z" }],
    costs = [{ "projectid": 100, "cost": 300 }, { "projectid": 100, "cost": 100 }, { "projectid": 200, "cost": 500 }],
    mergedData = function (p, c) {
        var obj = {},
            result = p.map(function (a) {
                obj[a.id] = { id: a.id, name: a.name, cost: 0 };
                return obj[a.id];
            });
        c.forEach(function (a) {
            obj[a.projectid].cost += a.cost;
        });
        return result;
    }(projects, costs);

document.write('<pre>' + JSON.stringify(mergedData, 0, 4) + '</pre>');

Answer №2

Here is a snippet of pseudo-code for handling projects and costs:

var projects = null;
$http.get('API/projects').then(function(response) {
        projects = JSON.parse(response.data);
        $http.get('API/costs').then(function(response) {
            var costs = JSON.parse(response.data);
            projects.forEach(function(project) {
                var sum = 0;
                costs.forEach(function(cost) {
                    if (project.id === cost.projectid) {
                        sum += cost.cost;
                    }
                });
                project.cost = sum;
            });
        };
    });
console.log(projects);

With some adjustments, this code should function correctly. There may be more efficient ways to achieve the same result.

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

Tips for organizing Protractor promises

I am currently experimenting with determining if an element is positioned at the bottom of a page in Protractor/Webdriver using promises. However, I feel like my current approach is quite messy and there must be a cleaner way to achieve this. describe(&ap ...

Application Layer Capability

I am currently in the process of developing an App that requires authentication. To ensure that the user is authenticated before changing routes and instantiating the route Controller, I need to implement a function that can retrieve the logged-in user fro ...

Can you please tell me the CSS pseudo element that corresponds to the AM/PM field in an <input type="time">

The issue with the am/pm display is dependent on the browser that the app is opened in. I am looking for a universal solution to ensure it does not appear in any popular browsers. Below is the HTML code for my input time field: <input type="time" for ...

Redis data retrieval is successful on the second attempt

I am utilizing a Redis database along with express routing to create an API. My stack includes node.js and ioredis as well. The process involves connecting to Redis, fetching keys related to a specific date, and then retrieving the data associated with th ...

Differences between ng build --prod and ng --build aot in Angular 7

Recently, I successfully built an Angular 7 application using the command ng build --prod. However, I am now facing a dilemma regarding ng build --aot versus ng build --prod. Our application is currently deployed on ..., and although it runs successfully ...

Sorting JSON data in EJS based on categories

Hello, I am facing a dilemma. I need to apply category filtering to a JSON file but I am unsure of how to proceed with it. For instance, I wish to filter the 'vida' category along with its description and price. I seem to be stuck at this junctu ...

The mobile web app on iOS is stuck in a never-ending loop of showing the

My mobile app is built using angular.js, Twitter Bootstrap, and grunt with a .NET back end. After logging in, the loading spinner keeps showing up constantly in the top nav next to the time and battery status. We make server calls at login through a factor ...

Issue with Plesk Obsidian, IISNode, and Express - application functioning solely in local environment

After setting up my Node.JS + Express.JS application on my server with IISNode and Plesk Obsidian, browsing the page in a browser triggers an error: I have already verified the permissions of the relevant folders and ensured that the "App Identities" have ...

Express.js routes are malfunctioning with jade/pug, causing frequent crashes and routing errors

Here is the code for my contact router: var express = require('express'); var router = express.Router(); /* GET users listing. */ router.get('/', function(req, res, next) { res.render('contact'); }); module.exports = rou ...

Tips on utilizing variables instead of static values when calling objects in JavaScript

How can I make something like this work? I tried putting the variable in [], but it didn't work. Can someone please help me out with this? Thank you. const obj = { car : "a" , bus: "b" }; const x = "car" ; ...

Urgent concern: the require function is being utilized in a manner that prevents the static extraction of dependencies [mysterious]

After implementing the magic-sdk version 8.0.1 on my project, I encountered the following warning message: warn - ./node_modules/magic-sdk/dist/es/index.js Critical dependency: require function is used in a way in which dependencies cannot be statically e ...

Saving persistent values in AngularJSIn AngularJS, you can

Can values or constants be stored in a recipe that includes all local storage values with assigned names, such as: username:$localstorage.get('M_NAME') mem_id:$localstorage.get('MEMBER_ID') position:$localstorage.get('M_POSITION&a ...

Synk: the presence of a self-signed certificate within the certificate chain

Recently, I've been encountering the error message Synk Protect is showing "self-signed certificate in certificate chain" when I try to run npm install on a project of mine. Would appreciate any help or tips on how to identify which out of the 984 pac ...

Is there a foolproof way to generate JSON data using PHP?

I am new to JSON and I have XML results that I want to convert to JSON format. The data is retrieved from a mySQL array. My issue arises when dealing with multiple nodes with the same name in the XML result, as shown below: <results> <result ...

Aligning angular bootstrap modal window in the center vertically

Is there a way to vertically center a modal window on the screen, regardless of the size of the content being displayed? I'm currently using an image as a modal window in my page, and while I was able to align it horizontally, I'm struggling to g ...

What is the best way to define an Angular UI Modal without using a controller?

Can the Angular UI Modal controller/object be declared outside of its triggering controller in a separate file without polluting the global namespace? Is it possible to declare the modal controller like a regular controller and pass parameters in from the ...

The successful JSON response in an Ajax request is not functioning as expected

I've set up a data table that allows users to add rows by clicking the "plus" button. This triggers an ajax request to a URL with the rowId as a parameter (which corresponds to the specific row where the button was clicked). I expect to receive a JSON ...

JavaScript encounters an Access Denied error when attempting to read data from a JSON file in

My code is experiencing issues on IE browser and Chrome, but works perfectly on FireFox. var currentPage = 1; var max = 0; var myList = []; var links = []; $.ajax({ cache: false, type : 'GET', crossDomain: true, ...

Utilizing children as a prop within a Vue component

In React, I can create a FancyList component like this: const FancyList : React.SFC<{},{}> ({children}) => ( <ul> {...children} </ul> ); const FancyListItem : React.SFC<{text: string}, {}> ({children}) => < ...

Why does JQuery AJAX require a nested DIV to function properly?

Consider the index.php file below : <!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-latest.min.js"></script> </head> <body> <form id="MY_FORM" action="./index.php" method="get" ...