phicon
phicon

Reputation: 3617

Angular 2 - Get one property of object into array

I have the following object

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

Now i want to fill an array with only the hours from the object.

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

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

How do i get the hours from the object into the hoursArray?

Upvotes: 0

Views: 4294

Answers (2)

Nitzan Tomer
Nitzan Tomer

Reputation: 164129

Use Array.prototype.map:

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

Also it can be:

private hoursArray: Array<string>;

Or simply:

private hoursArray: string[];

Upvotes: 3

Mateusz Woźniak
Mateusz Woźniak

Reputation: 1499

This way should work for you.

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

Upvotes: 0

Related Questions