简体   繁体   中英

How do I push an object in zeroth index of array inside an array in Angular

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?

You can test if it's empty, and first push an empty array if it is:

submit(data){
  const dataObj = {
    name: 'Test name',
    type: 'Test type',
  }

  if (!this.arr[0]) {
    this.arr.push([]);
  }

  this.arr[0].push(dataObj);
  console.log('Result array - ', this.arr);
}

You are also saying you want to push it to the 0th index of first array . So this solves the 'first array' part. If you really want to push it to the 0th index of the first array, you use unshift :

this.arr[0].unshift(dataObj);

You can use unshift for it.

const arr = [1, 2, 3];
arr.unshift(0); // [0, 1, 2, 3];

Please note that it is a mutating function.

You can also use:

const arr = [1, 2, 3];
[0].concat(arr); // [0, 1, 2, 3];

This doesn't mutate the existing array.

There are suprisingly multiple ways to enter an element in the 0th position. You could achieve it with push() and shift() like other answers have mentioned. You could also do it with splice() method.

 const arr1 = [1, 2, 3]; arr1.splice(0, 0, 4); // <-- enter in pos. 0 console.log('Position 0: ', arr1); const arr2 = [1, 2, 3]; arr2.splice(1, 0, 4); // <-- enter in pos. 1 console.log('Position 1:', arr2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM