I have a backend API which gives data in this format when it is not empty. I have to always push any new data coming from user into 0th index of first array.
[
[
{
name: 'Name 1',
type: 'Type 1'
},
{
name: 'Name 2',
type: 'Type 2'
}
],
[
{
name: 'Name 4',
type: 'Type 4'
},
{
name: 'Name 5',
type: 'Type 5'
}
]
]
The below code works fine with non empty data. But, if the API data is empty, it gives Cannot read property 'push' of undefined error.
arr: any = [];
constructor() {}
submit(data){
const dataObj = {
name: 'Test name',
type: 'Test type',
}
this.arr[0].push(dataObj)
console.log('Result array - ', this.arr)
}
I created a working example using Stackblitz. Could anyone please help?