2017-01-08 1 views
0

Ich habe folgendes ObjektAngular 2 - Holen Sie sich eine Eigenschaft des Objekts in einem Array

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

Jetzt i mit einem Array füllen wollen nur die Stunden vom Objekt.

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

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

Wie bekomme ich die Stunden vom Objekt in die StundenArray?

Antwort

2

Verwendung Array.prototype.map:

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

Auch kann es sein:

private hoursArray: Array<string>; 

Oder einfach:

private hoursArray: string[]; 
0

Auf diese Weise sollte für Sie arbeiten.

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); 
     } 
    }); 
} 
Verwandte Themen