Angular 2合并相同的变量号

时间:2018-12-08 11:09:35

标签: javascript angular typescript

我正在从这样的数据库中获取数字:

    getTeamPoints(team) {
console.log(team);
         let a = (<any>Object).values(team.tasks).reduce((total, entry) => total + entry.pt, 0);
        console.log('a = ',a)
    }

对于每个number,我得到value(仅示例为非真值):

a = 10;
a = 15;
a = 20;
a = 5;
a = 0;

如何将merge的{​​{1}}变成一个a的{​​{1}}?

编辑:console.log(team):

number

编辑:遍历团队:

10+15+20+5+0 = 50

edit:objectValues函数:

{"members":{"-LT8U_zn5T9HuSlh03lw":{"name":"Andrius"}},"name":"Frontas","tasks":{"-LT8UbPIJMrR52P4hvHJ":{"name":"Jobas","pt":5},"-LT8UcOAvqPk_o3fUl7y":{"name":"Jobas2","pt":5}}}

{"members":{"-LT8UenQm-WzElOQhIrX":{"name":"Tomas"}},"name":"Backas","tasks":{"-LT8UfmIezqiMDv3WCpA":{"name":"Jobas3","pt":5}}}

{"members":{"-LT986cZrN6Q1sqIjMZF":{"name":"AAA"}},"name":"Tetas","tasks":{"-LT988EvCySLOutd5AVK":{"done":true,"name":"Jobas","pt":15},"-LT989cIEqr4ObqNyfiA":{"done":false,"name":"XX","pt":16}}}

console.log(团队):

<mat-card-content *ngFor="let team of objectValues(project[2])>
    <h2 class="right-text">{{getTeamPoints(team)}}%</h2>
</mat-card-content>

2 个答案:

答案 0 :(得分:1)

这样更改您的组件:

<mat-card-content>
    <h2 class="right-text">
        {{ getProjectTeamsTotalPoints(objectValues(project[2])) }}
    </h2>
</mat-card-content>

然后在您的班级中添加以下方法:

getProjectTeamsTotalPoints(teams): number {
    return teams.reduce((total, team) => {
        if (!team || !team.tasks) {
            return total;
        }
        return Object.values(team.tasks).reduce((pts, task) => {
            return pts + task.pt;
        }, total);
    }, 0);
}

还更新您的objectValues函数以始终返回一个数组:

objectValues(obj) {
    return Object.values(obj || {});
}

基本上,您减少了团队数量,而每个团队都减少了他们的积分,这样您就可以获得项目的总摘要。

答案 1 :(得分:0)

您可以通过以下方式解决它:

let a = 0;
a += (<any>Object).values(team.tasks).reduce((total, entry) => total + entry.pt, 0);