I have a Stackblitz.com sample here https://stackblitz.com/edit/angular-xhulyo?file=app%2Fapp.component.ts, and I need to combine totals of users like dbrown or qadmin instead of displaying them on separate lines. It currently displays the results like this:
User Success Failure
dbrown 16 0
qadmin 4 0
dbrown 4 1
qadmin 21 2
administrator 42 0
cooper 8 0
ad.brown 7 0
and dbrown's totals should be 20 and 1 and qadmin's should be 25 and 2. You can see from the code that it's just iterating through the users variable. Here's the app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular 5';
users: any[] = [];
items: any;
ngOnInit() {
this.items = {"Users":{"InteractiveLogon":[{"UserName":"dbrown","Success":"16","Failed":"0"},{"UserName":"qadmin","Success":"4","Failed":"0"}],"NetworkLogon":[{"UserName":"dbrown","Success":"4","Failed":"1"},{"UserName":"qadmin","Success":"21","Failed":"2"},{"UserName":"administrator","Success":"42","Failed":"0"},{"UserName":"cooper","Success":"8","Failed":"0"},{"UserName":"ad.brown","Success":"7","Failed":"0"}]}};
for (let user of this.items.Users.InteractiveLogon)
this.users.push(user);
for (let user of this.items.Users.NetworkLogon)
this.users.push(user);
}
}
And here's the app.component.html:
<hello name="{{ name }}"></hello>
<p>
Start editing to see some magic happen :)
</p>
<hr>
<table *ngIf="users">
<thead>
<tr>
<th align=left>User</th>
<th>Success</th>
<th>Failure</th>
</tr>
</thead>
<tr *ngFor="let row of users" >
<td style="padding-right: 15px">{{row.UserName}}</td>
<td>{{row.Success}}</td>
<td>{{row.Failed}}</td>
</tr>
</table>
I've found issues like Combining JSON Data Sets and Sum of object properties within an array that talk about using properties like hasOwnProperty and the map and reduce functions but I'm not sure how to use them to combine totals of separate value pairs with the same name and how to total just those.
EDIT:
I went with a combination of contributors to make it more clear (for me). Comments are welcome if this is not the best way to do it. I got rid of the "this" operator too. New StackBlitz here. The combineUserTotals function looks like this:
combineUserTotals() {
let result: any, results: any[] = [];
this.users.map((user) => {
result = results.find(u => u.UserName == user.UserName);
if (!result)
results.push({ UserName: user.UserName, Success: Number(user.Success), Failed: Number(user.Failed) });
else {
result.Success += Number(user.Success);
result.Failed += Number(user.Failed);
}
});
return results;
}