2017-01-08 2 views
0

У меня есть следующий объектУгловое 2 - Получить одно свойство объекта в массив

export class HourPerMonth { 
    constructor(
     public year_month: string, 
     public hours: string, 
     public amount: string 
    ) { }; 
} 

Теперь я хочу, чтобы заполнить массив только часы от объекта.

private hourPerMonth: HourPerMonth[]; 
private hoursArray: Array<any>; 

getChartData() { 
    this.chartService.getHoursPerMonth().subscribe(source => { 
     this.hourPerMonth = source; 
     this.hoursArray = ? 
    }); 
} 

Как я могу получить часы от объекта в часахArray?

ответ

2

Использование Array.prototype.map:

this.hoursArray = source.map(obj => obj.hours); 

Также это может быть:

private hoursArray: Array<string>; 

Или просто:

private hoursArray: string[]; 
0

Этот способ должен работать для вас.

private hourPerMonth: HourPerMonth[]; 
private hoursArray: Array<any> = []; 

getChartData() { 
    this.chartService.getHoursPerMonth().subscribe(source => { 
     this.hourPerMonth = source; 
     this.hourPerMonth.forEach(hourPerMonth => { 
      this.hoursArray.push(hourPerMonth.hours); 
     } 
    }); 
} 
Смежные вопросы