Home > database >  How do I assign the values of an object array to another object array that has more properties?
How do I assign the values of an object array to another object array that has more properties?

Time:10-21

I am taking an array of Workouts and want to turn it into an array of RoutineWorkouts which has all of the properties of Workouts as well as "sets" and "reps". Then I want to display this array as a list on this page where I will be able to assign the reps and sets with ion-select.

create-routine.page.ts

 workoutR: any[];
 routineWorkouts: RoutineWorkout[] = [];
 sets = [2, 3, 4];
 reps = [4, 6, 8, 10, 12, 16, 20];

ionViewWillEnter(): void{
   this._subscription = this.workoutService.getMessage().subscribe((bWorkout:Workout[]) => {
     this._receivedWorkouts = bWorkout;
   });
   console.log(this._receivedWorkouts);
   this.workoutR = this._receivedWorkouts;  
 }

To display it on the page, I have *ngFor="let workout of workoutR".

Workout and RoutineWorkout models

export class Workout {
    id: number;
    name: string;
    muscle: string;
}
export class RoutineWorkout {
    id: number;
    name: string;
    sets: number;
    reps: number;
}

I have tried this, but keep getting this error. How would I assign the values of the array that I created as new RoutineWorkouts so that I can assign reps and sets?

CodePudding user response:

You cannot assign a variable of one type(Interface) to another. Instead you can create a new variable with same type and assign them back to the required one.

Here this.routineWorkouts is of Interface RoutineWorkout[] and this._receivedWorkouts is of type Workout[]

Pseude Code

const newReceivedWorkouts: RoutineWorkout[] = this._receivedWorkouts.map(({id, name}) => ({ id, name, sets: 0, reps: 0}))
this.routineWorkouts = newReceivedWorkouts;

Here this.routineWorkouts and newReceivedWorkouts are of same type, hence they are assignable.

Hope this will work for you.

  • Related