角度4-从模型的嵌套数组中添加数字

时间:2018-11-27 07:03:00

标签: arrays angular typescript

我有一个Model数组。此模型的每个对象都有另一个模型的数组。 我想从嵌套数组中添加所有相应的数字变量。我的代码如下所示

型号

TimesheetLogged.ts

export interface TimesheetLogged {
    ProjectId: string,   
    MondayHours: number,
    TuesdayHours: number,
    WednesdayHours: number,
    ThursdayHours: number,
    FridayHours: number,
    SaturdayHours: number,
    SundayHours: number   
}

Project.ts

import { TimesheetLogged } from "./TimesheetLogged";

export interface Project {
    ProjectId: number;  
    TimeLoggedHours: TimesheetLogged[];   
}

组件中的代码片段

public Projects: Project[];
//Get projects data from database and subscribe to Projects object  Successfully

let chartData: Array<number> = [];
    let mon:number= 0;
    let tue:number= 0;
    let wed:number= 0;
    let thu:number= 0;
    let fri:number= 0;
    let sat:number= 0;
    let sun:number= 0;

    this.Projects.forEach((empHours) => {
        empHours.TimeLoggedHours.forEach((hours) => {
            a => {
                mon += a.MondayHours;
                tue += a.TuesdayHours;
                wed += a.WednesdayHours;
                thu += a.ThursdayHours;
                fri += a.FridayHours;
                sat += a.SaturdayHours;
                sun += a.SundayHours;
            }  
        });            
    });
    chartData.push(mon);
    chartData.push(tue);
    chartData.push(wed);
    chartData.push(thu);
    chartData.push(fri);
    chartData.push(sat);
    chartData.push(sun); 

但是我得到的所有数字变量的总和为

[对象数组] [0,0,0,0,0,0,0]

此代码中需要进行任何更新。任何其他更简单的解决方案都欢迎。

1 个答案:

答案 0 :(得分:0)

删除a => lambda,然后使用mon += hours.MondayHours等。

否则,在第二个forEach中,您只需创建一堆lambda函数,而不用更改montue等。

this.Projects.forEach(empHours => {
        empHours.TimeLoggedHours.forEach(hours => {
                mon += hours.MondayHours;
                tue += hours.TuesdayHours;
                wed += hours.WednesdayHours;
                thu += hours.ThursdayHours;
                fri += hours.FridayHours;
                sat += hours.SaturdayHours;
                sun += hours.SundayHours;
        });            
    });