簡體   English   中英

如何將 object 推送到 Angular 中的數組內的數組的第零索引中

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

我有一個后端 API 當它不為空時以這種格式提供數據。 我必須始終將來自用戶的任何新數據推送到第一個數組的0th個索引中。

[
  [
   {
      name: 'Name 1',
      type: 'Type 1'
    },
    {
      name: 'Name 2',
      type: 'Type 2'
    }
  ],
  [
    {
      name: 'Name 4',
      type: 'Type 4'
    },
    {
      name: 'Name 5',
      type: 'Type 5'
    }
  ]
]

下面的代碼適用於非空數據。 但是,如果 API 數據為空,則會給出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)
  }

我使用 Stackblitz 創建了一個工作示例 有人可以幫忙嗎?

您可以測試它是否為空,如果是,則首先推送一個空數組:

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

你還說你想把它推到0th index of first array 所以這解決了“第一個數組”部分。 如果你真的想把它推到第一個數組的0th個索引,你可以使用unshift

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

你可以使用 unshift 。

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

請注意,它是一個變異的 function。

您還可以使用:

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

這不會改變現有數組。

在第 0 個 position 中輸入元素的方法有很多種。 您可以使用push()shift()來實現它,就像其他答案提到的那樣。 您也可以使用splice()方法來做到這一點。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM