calculating the sum of all individual items within an object

Is there a way to map an object, add specific values, and then calculate the total? I am looking to map the object below and extract certain items. Any suggestions?

Object:

  [
    {
        "description": "Current Term",
        "monthlyRent": 29971.599999999995,
        "monthsInPeriod": 41.7,
        "rentInPeriod": null
    },
    {
        "description": "Current Term - Rent Adjustment",
        "monthlyRent": 31470.180000000004,
        "monthsInPeriod": 47.96666666666667,
        "rentInPeriod": 1509519.634
    }
]
29971.599999999995 + 41.7   = 30,012
31470.180000000004 + 47.96666666666667 =  31,517

Desired Result: should be

 total = 30,012 + 31,517

Answer №1

To achieve the desired outcome, you can utilize the map and reduce methods:

const data = [
    {
        "description": "Current Term",
        "monthlyRent": 29971.599999999995,
        "monthsInPeriod": 41.7,
        "rentInPeriod": null
    },
    {
        "description": "Current Term - Rent Adjustment",
        "monthlyRent": 31470.180000000004,
        "monthsInPeriod": 47.96666666666667,
        "rentInPeriod": 1509519.634
    }
];
const total = data
  .map(item => item.monthlyRent * item.monthsInPeriod)
  .reduce((currentValue, acc) => acc + currentValue);

If you prefer to add the monthlyRent and monthsInPeriod instead of multiplying them, simply replace the map with

item.monthlyRent + item.monthsInPeriod
.

Answer №2

The map() method generates a fresh array filled with the outcomes of invoking a specified function on each item in the original array. For more details, check out this example.

The reduce() method executes a user-defined “reducer” callback function on every element of the array, using the result from the previous calculation for the current element. The final output of applying the reducer to all elements is a single value. View an example here.

You can create a solution by utilizing both methods like this:

let arry = [
    {
        "description": "Current Term",
        "monthlyRent": 29971.599999999995,
        "monthsInPeriod": 41.7,
        "rentInPeriod": null
    },
    {
        "description": "Current Term - Rent Adjustment",
        "monthlyRent": 31470.180000000004,
        "monthsInPeriod": 47.96666666666667,
        "rentInPeriod": 1509519.634
    }
];

let total = arry 
  .map(obj=> obj.monthlyRent + obj.monthsInPeriod)
  .reduce((value, previousValue) => previousValue + value);

An alternative approach is to simply use a forEach loop:

 let total2:number=0;
    for (let i = 0; i < this.arry.length; i++) {
       let val = this.arry[i].monthlyRent + this.arry[i].monthsInPeriod;
       total2 = total2+val       
    }

Feel free to access the included StackBlitz here.

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

Ensuring Uniform Data Types Across Objects (Using Typescript)

After much trial and error, I have finally reached this point where everything seems to be working perfectly. function test<types extends Record<string,any>>(dict: dictionary<types>){} type dictionary<types extends Record<string, a ...

Disabling Angular routerlink tabindex additions can be done by modifying the application's

While the angular guide to accessibility covers many important topics, it fails to address the issue of preventing tabindex from being added on every button with a routerlink. This has resulted in my app having tabindex="0" on buttons throughout. ...

Cross-Origin Resource Sharing problem in HttpResponse Activity

Currently, I am utilizing the Elsa-Core - AspnetCore Monolith Dashboard example. Workflow: The issue arises in the HttpReponse Activity, while the HttpEndpoint functions correctly. I am encountering an error on the client side which I am unable to captu ...

Tips for concealing a dynamic table element in Angular 9

I have dynamically generated columns and rows in a table. Here is my HTML for the table component: <table id="tabella" class="table table-striped table-hover"> <thead class="thead-dark"> <tr> <th *ngFor="let header of _ob ...

Attempting to redeclare a previously exported variable will result in an error stating: "Cannot

I'm currently facing an issue with a npm module located in a different directory that I've linked to another project using npm link. Despite successfully compiling the typescript, when I try to import the module and use its function, I encounter ...

Multiple consecutive requests within another (Angular)

Currently, I am deepening my understanding of rxjs and struggling to find an efficient way to manage a sequence of requests. For instance, let's consider the UserService where one of its functions retrieves a user object based on the user id. After ob ...

Deactivate multiple input fields by utilizing various radio buttons

I need help with enabling and disabling input fields based on radio button selection. When the first radio button is selected, I want to disable three input fields, when the second is selected, only two specific input fields should be enabled (SHIFT START ...

index signature in TypeScript is an optional feature

Is it possible to create a type with optional namespaces in TypeScript? export interface NodesState { attr1: number; attr2: number; attr3: number; } The goal is to allow users to namespace the type like this: { namespace1: { attr1: 100, ...

Obtain unique entries from a Firestore collection search

Seeking assistance in filtering an observable to only contain unique records. I am using the observable in an angular mat-autocomplete with an async pipe and querying firebase based on the user's input. The code for the mat-autocomplete template: ...

Angular view not reflecting changes made to the model

Here is a straightforward Angular application I created to play audio using the JavaScript web Audio Object: app.component.ts export class AppComponent { title = 'media player'; audio; currentTime: number; constructor() { this.audi ...

Instantiate an object of the ng.IQService type without using injection

Is it possible to define a local variable in the controller of type ng.IQService ( private _q: ng.IQService;) without requiring injection? My technology stack includes typescript and angular. The reason for this requirement is due to existing legacy code ...

Does Angular automatically check all checkboxes when one checkbox is checked?

When using checkboxes in Angular to select a skillSet, I am encountering an issue where checking one checkbox ends up checking all checkboxes. How can this problem be resolved? Below is the skillSet array in component.ts: skillSet: Array<string> = ...

Angular 5% symbol pipe not displaying correct digitInformation

When utilizing an Angular 5 template, consider the following scenario: {{0.7 | percent:'1.2-5'}} The anticipated outcome is 70.00% Conversely, observe the result from the following code: {{0.07 | percent:'1.2-5'}} Unexpectedly, the ...

Troubleshooting Angular 2 with TypeScript: Issue with view not refreshing after variable is updated in response handler

I encountered a problem in my Angular 2 project using TypeScript that I could use some help with. I am making a request to an API and receiving a token successfully. In my response handler, I am checking for errors and displaying them to the user. Oddly en ...

Having difficulty initializing a constant object in TypeScript

Encountering an error while attempting to compile my code using Angular 7.2.0 and TypeScript version 3.2.2: Error TS1005: ',' expected.**… The issue seems to be arising from the line where I am trying to define a const object. addAppareil( ...

Using TypeOrm QueryBuilder to establish multiple relations with a single table

Thank you for taking the time to read and offer your assistance! I am facing a specific issue with my "Offer" entity where it has multiple relations to "User". The code snippet below illustrates these relationships: @ManyToOne(() => User, (user) => ...

Using an external file to handle the joining of a Socket.io room upon an HTTP request in an

I am finding myself in a state of confusion with this Node.js, Angular 13, and Socket IO situation. To start off, let's assume that all necessary information is being stored in a database, such as roomId, roomOwner, username, and so on. Now, let&apos ...

Generics in Typescript implemented for a React component that accepts an array of records along with an array of

I am currently working on developing a straightforward typed react component designed to display a table from an array of objects. The input data is structured as follows: // array of records containing data to render in the table data = [ { one: 1, ...

Accessing the URL causes malfunctioning of the dynamic routing in Angular 2

I am currently working on implementing dynamic routing functionality in my Angular application. So far, I have successfully achieved the following functionalities: Addition of routing to an existing angular component based on user input Removal of routin ...

Exploring Angular 6: Unveiling the Secrets of Angular Specific Attributes

When working with a component, I have included the angular i18n attribute like so: <app-text i18n="meaning|description"> DeveloperText </app-text> I am trying to retrieve this property. I attempted using ElementRef to access nativeElement, bu ...