Guide on calculating the total of an object's attributes in Angular

Given a JSON object structured as follows:

{
  "baskets": [{
    "id": 127,
    "name": "name 1",
    "kpIs": [{
      "id": 419,
      "name": var a1, "incentive": 0, "target": "0", "actual": 0, "description": null
    }, {
      "id": 420,
      "name": var a2, "incentive": 0, "target": "0", "actual": 0, "description": null
    }],
    "percentage": 0
  }, {
    "id": 128,
    "name": "name 2",
    "kpIs": [{
      "id": 421,"name": "var b1","incentive": 0,"target": "0","actual": 0, "description": null
    }, {
      "id": 422, "name": "var b2","incentive": 0,"target": "3", "actual": 0, "description": null
    }, {
      "id": 423, "name": " var b3","incentive": 0,"target": "5.6","actual": 0,"description": null
    }, {
      "id": 424,"name": " var b4", "incentive": 0, "target": "2", "actual": 0, "description": null
    }],
    "percentage": 0
  }],
  "id": 23,
}

The objective is to calculate the combined totals (target, incentive and actual) for each nested object, as well as the overall totals for the entire object. The object has been linked to a table: https://i.sstatic.net/Gcai3.png.

            <table class="table table-responsive table-bordered table-striped w-100%">
                <thead>
                    <tr>
                        <th data-label="KPI Basket" scope="col">KPI Basket</th>
                        <th data-label="KPIs" scope="col">KPIs</th>
                        <th data-label="Tgt figures" scope="col">Target</th>
                        <th data-label="Tgt figures" scope="col">Actual</th>
                        <th data-label="Incentive" scope="col">Incentive</th>
                        <th data-label="% of Total" scope="col">Total</th>
                    </tr>
                </thead>
                 <tbody *ngFor="let data of document.baskets; let i = index">
                    <tr style="margin: auto;" *ngFor="let obj of data.kpIs">
                        <td>{{ data.name }}</td>
                        <td>{{ obj.name }}</td>
                        <td>{{ obj.target }}</td>
                        <td>
                            <input
                                type="number"
                                [(ngModel)]="obj.actual"
                                name="actual{{j}}"
                                class="form-control"
                                (change)="performOperations(obj.actual, obj.target, obj.incentive  )"
                            />
                        </td>
                        <td>{{ obj.incentive }}</td>
                        <td>
                            <input
                            type="number"
                            [(ngModel)]="individualTotal"
                            name="individualTotal{{j}}"
                            class="form-control"
                        />
                        </td>
                    </tr>
                    <tr>
                        <th data-label="KPI Basket" scope="row"></th>
                        <strong> <td data-label="KPIs">Sub-total</td></strong>
                        <td data-label="Incentive">{{ subTotal }}</td>
                        <td data-label="% of Total"></td>
                        <td data-label="Tgt figures"></td>
                        <td data-label="Tgts"></td>
                    </tr>
                </tbody> 
                <tbody>
                    <tr>
                        <strong>
                            <tr data-label="KPIs">
                                Total
                            </tr></strong
                        >
                        <td data-label="KPI Basket" scope="row"></td>
                        <td data-label="Incentive"></td>
                        <td data-label="% of Total"></td>
                        <td data-label="Tgt figures">35</td>
                        <td data-label="Tgts">35</td>
                    </tr>
                </tbody>
            </table>

The subtotal field is meant to display the summed totals for the objects named "name 1" and "name 2." The total field should then show an aggregate total for the entire object. Any suggestions on how to accomplish this?

Answer №1

Following the calculation provided in the comment,

The sub total represents the sum of actual values entered in a text box for each column. The total is calculated by multiplying the actual value with the corresponding incentive - user9913710

const data = {
  baskets: [{
      id: 127,
      name: "name 1",
      kpIs: [{
          id: 419,
          name: "var a1",
          incentive: 0,
          target: 0,
          actual: 0,
          description: null,
        },
        {
          id: 420,
          name: "var a2",
          incentive: 0,
          target: 0,
          actual: 0,
          description: null,
        },
      ],
      percentage: 0,
    },
    {
      id: 128,
      name: "name 2",
      kpIs: [{
          id: 421,
          name: "var b1",
          incentive: 0,
          target: 0,
          actual: 0,
          description: null,
        },
        {
          id: 422,
          name: "var b2",
          incentive: 0,
          target: 3,
          actual: 0,
          description: null,
        },
        {
          id: 423,
          name: " var b3",
          incentive: 0,
          target: 5.6,
          actual: 0,
          description: null,
        },
        {
          id: 424,
          name: " var b4",
          incentive: 1,
          target: 2,
          actual: 2,
          description: null,
        },
      ],
      percentage: 0,
    },
  ],
};

const basketTotal = data.baskets.map((basket) => {
  // total = actual * incentive;
  basket.kpIs = basket.kpIs.map((kpi) => ({
    ...kpi,
    total: kpi.actual * kpi.incentive,
  }));
  // sub-total = sum(actual);
  const subTotal = basket.kpIs.reduce((total, kpi) => {
    return total + kpi.actual;
  }, 0);

  return { ...basket, subTotal };
});

console.log(JSON.stringify(basketTotal, null, 2));

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

Error 500 occurred when attempting to access an external PHP file

I am currently utilizing WP Web Scraper version 3.2. When I place the shortcode or template tag (php code) directly into my page, the plugin functions correctly and displays the values. However, when I attempt to include the template tag in an external php ...

I must determine whether the contents of an array exceed zero

THE SUMMARY: I have three value numbers for an array. If the total addition of the array's elements is greater than 0, I need to display "el funcionamiento no es infinito", otherwise "es infinito". It seems that it's not working because I belie ...

What sets 'babel-plugin-module-resolver' apart from 'tsconfig-paths'?

After coming across a SSR demo (React+typescript+Next.js) that utilizes two plugins, I found myself wondering why exactly it needs both of them. In my opinion, these two plugins seem to serve the same purpose. Can anyone provide insight as to why this is? ...

Error: There was a problem trying to import the `.d.ts` file

Software Stack Vue version 3.2.19 @vue/test-utils version 2.0.0-rc.15 Typescript version 4.1.6 Issue Description Encountering an error when running the command vue-cli-service test:unit --no-cache. Please refer to the TypeError screenshot (link to Con ...

Executing a function in the Angular 5 template based on the results of an observable leads to multiple function calls

Custom HTML Template <div *ngFor="let element of convertObjectToArray(observerable_value)"> {{element.name}} </div> Custom Component convertObjectToArray(obj) { const arr = Object.values(obj); return arr; } Seeking Solution I ...

I am unable to pass a variable through a callback, and I cannot assign a promise to a

Currently, I am facing a challenge with my code where I need to loop through a hard-coded data set to determine the distance from a user-entered location using Google's web API. The issue lies in passing an ID variable down through the code so that I ...

A guide on connecting multiple select components to a unified Angular 6+ reactive form without triggering redundant updates

I am facing an issue where I need to connect multiple input components to a single angular reactive form, but encounter two main obstacles: By default, only the form in which user input occurs gets updated If I use [(ngModel)] it does work, but it trigge ...

Using Javascript to restore image to its original state in OpenCart 2.3

I recently created a JavaScript function that successfully replaces the main image on a product page with a different image when clicked. While this feature is functioning perfectly, I am struggling to make the original image return once the mouse leaves t ...

I was able to resolve the display block issue, but I suspect there might be a mistake in my conditional statement

Looking for some help here - I want my user prompts to be displayed in block form, while the user story and error messages should remain hidden until the user enters their inputs. However, my script seems to be malfunctioning and I can't figure out wh ...

Angular Universal (SSR) 'Selectors were not applied as rules were not followed'

Steps to Reproduce: ng new testproject --style scss cd testproject ng add @ng-bootstrap/ng-bootstrap npm run build This issue is not limited to ng-bootstrap, it can occur with other frameworks like bootstrap or tailwind that use SCSS. Error Description: ...

Loop through the tabs array and display varying views based on conditionals

I am currently working on building tabs and tab panels iteratively to display information, but I am facing issues in getting the desired output. For each name in a list, I need to create a tab and a corresponding tab panel underneath it. For example, the ...

Issue occurring while trying to select an item from the dynamically generated options using AJAX

A JavaScript function is used in this code to select a specific option, with the option value being specified within a hidden element: $("select").each(function() { var id = $(this).attr('id'); var source = 'input:hidden[na ...

How to detect a click event in any area of an Angular2

Hey there, I'm new to typescript and angular 2 and I've encountered an error in my code. Can someone lend me a hand in fixing this? import { Component, HostListener } from '@angular/core' export class TooltipComponent { public sh ...

Creating a secured page with Node.js and Express: Password Protection

I am a beginner with node.js/express! Currently, I am working on developing a chat site along with a chat admin site. When I navigate to _____:3000/admin, it prompts me for a password through a form. I am looking for a way to verify if the entered passwor ...

Prevent Xdebug from processing multiple requests

One recurring issue I encounter in my app is calling an API endpoint every 60 seconds. However, when I attempt to debug using Xdebug, stepping through the controller associated with that endpoint often takes longer than a minute. This results in another re ...

Navigating back to the beginning of the webpage following the completion of a form submission utilizing Master Pages and Ajax

I am having an issue with my ASP.NET 4.0 page where I want to reset it to the top after a form submission so that the validation summary can be displayed properly. The setup involves using Ajax and a master page with the following simplified code: <f ...

Tips for updating an object with a narrowed type property in TypeScript

Is it possible to conditionally narrow the type of object properties without causing an error when reassigning the whole object to another variable? type A = { prop: string | number; } type B = { prop: string; } function f(a: A) { if (typeof a.pro ...

The error message `fablinker.php:343 Uncaught TypeError: $(...).dialog is not a function` indicates that

When attempting to call a function on click, I'm encountering an error in the console. I've researched various solutions on Stack Overflow such as checking for jQuery duplication, but haven't had success. Any suggestions? https://i.ssta ...

Attempting to transfer various variables from several windows using AJAX

Is it possible to pass multiple variables from two different windows into the same PHP script? If not, what would be the best approach to take? Thank you. verifyemail.html <script type = "text/javascript" src = "js/js_functions.js"></script> ...

Node.js Mongoose MongoDB causing issues with bodyparser

Combining two different applications - an authentication app and a to-do app where users input data and the app displays it. Both apps work fine separately, but after merging them, there is a parse error in the second app. The issue seems to be related to ...