【发布时间】:2018-09-19 15:40:07
【问题描述】:
我在这里有一个 Stackblitz.com 示例 https://stackblitz.com/edit/angular-xhulyo?file=app%2Fapp.component.ts,我需要合并用户总数,例如 dbrown 或 qadmin,而不是在单独的行中显示它们。它目前显示的结果如下:
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
dbrown 的总数应该是 20 和 1,qadmin 的总数应该是 25 和 2。您可以从代码中看到它只是在遍历 users 变量。这是 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);
}
}
这里是 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>
我发现了诸如 Combining JSON Data Sets 和 Sum of object properties within an array 之类的问题,它们谈论使用诸如 hasOwnProperty 和 map 和 reduce 函数之类的属性,但我不确定如何使用它们来组合具有相同名称的单独值对的总数以及如何合计这些。
编辑:
我与多个贡献者一起使用以使其更清晰(对我而言)。如果这不是 最好的 方法,欢迎发表评论。我也摆脱了“this”运算符。新的 StackBlitz here。 combineUserTotals 函数如下所示:
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;
}
【问题讨论】:
-
我正在尝试理解您的问题。你会在 html 中只有一行代码,还是除了求和 (n+(n-1)) 之外的所有用户?
-
不在乎。但我认为最好在打字稿代码中将用户变量中的用户组合起来。
标签: angular typescript angular5