0

I want to create an array of objects inside object.Like this

MyMainObject: {
myArray : [{name:string, available:boolean}]
}

And push values dynamically to the array

3
  • 1
    Your question is not clear. Can you describe little more? Commented Sep 4, 2020 at 16:04
  • Hi i want to declare and push array of objects inside an object. MyObject: { myarray : [{name:string, available:boolean}] }]}. In this manner Commented Sep 4, 2020 at 16:05
  • You can use array:any[] or create a class e.g product containing the objects in your array and declare array:product [] Commented Sep 4, 2020 at 16:07

2 Answers 2

0

First create interface

export interface MainObject {
  myArray: {name: string, available: boolean}[];
}

Then use that interface in component.

export class MyComponent {
   MyMainObject: MainObject = {} as MainObject;

constructor() {
    this.MyMainObject.myArray.push({ name: 'name', available: true });
    console.log(this.MyMainObject);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0
//Simply declare Object like inside class

    MyMainObject: {
    myArray : []
    };

//nd push value dynamically like inside any method

    if(condition){
    this.MyMainObject['myArray'].push(
    {name:string, available:boolean}
    )
    }

2 Comments

Facing issue: Type 'string' is not assignable to type 'never'. Code-Ref(Stackblitz)
Can you please post your code?