AngularJS JSON data computation

As I delve into learning angularjs (not 2), one of the challenges I face is calculating the total amount for a customer order. The data I'm working with is structured as follows:

var clients = [
            {
                id: 1, 
                joined: '2000-12-02', 
                name:'John', 
                city:'Chandler', 
                orders: [
                    {
                        id: 1,
                        product: 'Shoes',
                        total: 9.9956
                    }
                ]
            }, 
            {
                id: 2, 
                joined: '1965-01-25',
                name:'Zed', 
                city:'Las Vegas', 
                orders: [
                    {
                        id: 2,
                        product: 'Baseball',
                        total: 9.995
                    },
                    {
                        id: 3,
                        product: 'Bat',
                        total: 9.995
                    }
                ]
            }
]

With a controller and factory in place to handle this data...

Here's how my controller code looks like:

(function() {

    var ClientsController = function ($scope, $log, clientFactory) {
        $scope.sortBy = 'name';
        $scope.reverse = false;
        $scope.clients = [];

        function initialize () {

          clientFactory.getClients()
          .success(function(clients) {
              $scope.clients = clients;

          })
          .error(function(data, status, headers, config){
              $log.log(data.error + ' ' + status );

          });

      }

      initialize();

      $scope.doSort = function(propName) {
         $scope.sortBy = propName;
         $scope.reverse = !$scope.reverse;
      };

  };

  ClientsController.$inject = ['$scope','$log' ,'clientFactory'];

  angular.module('clientsApp')
    .controller('ClientsController', ClientsController);

}());

This is how my view has been designed:

<h2>Clients</h2>
Filter: <input type="text" ng-model="clientFilter.name" />
<br /><br />
<table>
    <tr>
        <th ng-click="doSort(name)">Name</th>
        <th ng-click="doSort(city)">City</th>
        <th ng-click="doSort(joined)">Joined</th>
        <th>&nbsp;</th>
    </tr>
    <tr ng-repeat="cli in clients | filter:clientFilter | orderBy:sortBy:reverse">
        <td>{{ cli.name }}</td>
        <td>{{ cli.city }}</td>
        <td><a href="#/orders/{{ cli.employeeid }}">View Orders</a></td>
    </tr>
</table>
<br />
<span>Total clients: {{ clients.length }} </span>

Now, if we look at adding an order total column, here's what I think could be the right approach:

clientFactory.getClients()
    .success(function(clients) {
        for(var i = 0; i < clients.length; i++) {
            var currentClient = clients[i];
            var clientOrderTotal = 0;

            if (currentClient.orders) {
                for (var j = 0; j < currentClient.orders.length; j++) {
                    clientOrderTotal += parseFloat(currentClient.orders[j].total);
                }
            } else {
                clientOrderTotal = 0;
            }
            clients[i].orderTotal = clientOrderTotal;
            console.log(currentClient.lastname+ " total: " + clientOrderTotal);
        }
        // After the execution of this logic, update your $scope's clients object.
        $scope.clients = clients;
    })

Answer №1

If you're looking to calculate the total amount per customer, a simple solution is to use a nested for loop:

.done(function(customers) {
    for(var i = 0; i < customers.length; i++) {
        var currentCustomer = customers[i];
        var customerTotal = 0;
        for (var j = 0; j < currentCustomer.orders.length; j++) {
            customerTotal += currentCustomer.orders[j].total;
        }
        customers[i].orderTotal = customerTotal;
        console.log(currentCustomer.name + " total: " + customerTotal);
    }
    // Update $scope's customers with the modified object after executing this logic.
    $scope.customers = customers;
}

Answer №2

To simplify things and enhance functionality, consider creating a custom filter with AngularJS while utilizing lodash:

angular.module('customersApp', [])
.filter('customerTotal', function() {
  return function(customer) {
    return _.reduce(customer.hours, function(sum, hours) {
      return sum + parseInt(hours.billableHours);
    }, 0);
  };
});

Once created, you can implement the custom filter like this:

<td>{{ currentCustomer.name }} total: {{ customerData | customerTotal }}</td>

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 method can I utilize in Powershell to filter out specific key names from a JSON file?

Attempting to shrink a large 700MB JSON file, which is a scaled-down version of the file found here: The goal is to eliminate unnecessary data by excluding certain keys such as hypernyms, pos, categories, and more. However, previous attempts at this using ...

What is the best way to use jQuery to find and select an "a" tag that links to a file with a specific

My goal is to select links that have different types of files using jQuery: jQuery('a[href$=".pdf"], a[href$=".doc"], a[href$=".docx"], a[href$=".ppt"], a[href$=".pptx"], a[href$=".xls"], a[href$=".slxs"], a[href$=".epub"], a[href$=".odp"], a[href$=" ...

Display various images based on different device orientations in UIWebView

Is there a way to display varying images in my HTML on a UIWebView, depending on the orientation of an iPhone? (I apologize if this question seems basic...) ...

The FuelUx scheduler forgets which day we've chosen when selecting weekly recurrence

When using the fuelUX scheduler, I noticed that after calling the method $('#myscheduler').scheduler("value","JSON VALUE") and selecting a weekly recurrence pattern, the information of the day gets lost. For example, if my input for the recurrenc ...

What is the best way to retrieve the total number of nested objects within an object?

I'm trying to figure out how to get the number of nested objects in the object a. a = { firstNested: { name: 'George' } secondNested: { name: 'James' } } I thought about using .length, which is typ ...

Automating the deployment of a vue.js app using GitLab CI/CD pipeline to deploy to

Currently experiencing an issue with the pipelines involving my YAML file that automates deployment of a Vue app to Firebase. Despite including scripts in the file and setting up the Environment variable FIREBASE_TOKEN on GitLab, pushing the code to a GitL ...

Is it possible to deactivate a button using jQuery without changing its visibility to transparent?

In my current project, I am utilizing jQuery and exploring its unique methods. I have a scenario where I need to disable two buttons based on a specific condition: if (...condition...) { $('button#submit, #hint').prop("disabled", true); } Ho ...

Having issues with images not loading and receiving a 401 error with the API while using Vite in a production build

While working on my React project with Vite, I've encountered a few challenges during the production build process. Everything seems to be running smoothly when I use npm run dev, but when I try to build the project using npm run build and then previ ...

Using Gson library for JSON parsing in Android application and encountering an issue

After executing a Web Service, I received a JSON response. However, when trying to convert this JSONObject (org.json.JSONObject) into a specific object using the Gson library, my application crashes unexpectedly. The error message I receive is: { "atribut ...

In Flow, how is the asterisk (*) type utilized and what is its counterpart in TypeScript?

My expertise lies mostly in TypeScript, but I recently came across Flow which seems quite similar to TS in many aspects. However, one thing that caught my attention is the asterisk (*) type in Flow. Initially, I thought it was just another way of represent ...

Issue with ng-grid in AngularJS: Data does not appear after resizing columns

Currently, I am encountering a problem where ng-grid data is not being displayed when column resizing occurs after changing the column names. To demonstrate this issue, I have created a plunkr at - http://plnkr.co/edit/eV9baoDOV9A46FZmKW8G?p=preview I wo ...

Experience a dynamic sliding effect when hiding elements with AngularJS using the ng-hide directive and ng

If you take a look at my jsfiddle http://jsfiddle.net/99vtukjk/, you'll see that currently, when clicking on the left or right text, the hide animation moves upwards. Is there a way to change this animation to slide and fade to the left menubar instea ...

The transition from Vuetify3's VSimpleTable to VTable is ineffective and unsuccessful

The v-simple-table component has been renamed to v-table Old code that was using v-simple-table may not work correctly after the renaming. It is recommended to use v-data-table with the same data, as it works correctly. https://i.sstatic.net/3GVdYMWl.png ...

Utilizing prototype JS to create a dynamic floating widget or banner

I recently developed a custom script based on the original jQuery code found at this link: However, I encountered issues when attempting to implement it with prototype JS. Specifically, there seems to be accuracy problems with calculating the upper and lo ...

Retrieving attribute values when using the .on function in jQuery

I currently have 10 links with the following format: <a href="#" data-test="test" class="testclass"></a> as well as a function that looks like this: $(document).on("click", ".testclass", function () { alert($(this).attr('data-t ...

Tips for sending a property to a function that is imported and produces a component in React

I need help figuring out how to pass an argument back to my component library that is imported in a parent app as a dependency. The specific issue arises when I am trying to implement a brand concept in the theme object. The goal is to switch the theme bas ...

Leveraging NodeJS to handle server-side tasks and operations

Background: I am exploring the use of NodeJS for a project that involves scraping and storing content in Mongo. This process needs to be automated according to a set schedule. In addition, I need functions that can extract items from the Mongo database, o ...

Error SRVE0199E: The output stream has already been obtained while calling $.getJSON

Currently, I am working on a project using Spring 4.0.2 and WebSphere Application Server (WAS) 7. My goal is to retrieve a JSON object from a Spring servlet. The response should be straightforward, and I don't believe the error lies in any syntax iss ...

Transforming Business Hours Data into JSON Object in SQL Server

When I'm extracting fields from the database, my most basic query typically looks like this: SELECT DISTINCT [BranchCode] ,[Weekday] ,[OpenTime] ,[CloseTime] FROM [Departments] WHERE [BranchCode] like '%1001.0000%' This ...

What is the process for setting a specific version of Node for a project on my local machine?

I am currently facing an issue with setting up Node across multiple developers' machines for a project. The challenge lies in the fact that not all team members are experienced in Node or JavaScript, and we need to ensure that everyone has the correct ...