简体   繁体   English

如何将数组推入嵌套数组?

[英]How to push arrays into a nested array?

I am trying to push multiple arrays into the column section. 我正在尝试将多个数组推入列部分。

  .then(body => {
    this.options = {
      padding: {
        left: 100,
        right: 100
      },
      data: {
        columns: [
        ],
      }
     }
    }

I have an array that contains a list of arrays. 我有一个包含数组列表的数组。

let new_array = {['test1', 2,3,5,6], ['test2', 5,3,9,6], ['test3', 1,2,5,2]}

I tried to write a function to push the arrays into columns, but I'm not sure what I'm doing wrong. 我试图编写一个将数组推入列的函数,但是我不确定自己做错了什么。 I'm not sure how to push things into columns. 我不确定如何将事情推入列中。

function populateColumn(new_array) {
  for (var i in new_array) {
    this.options['data']['columns'].push(new_array[i]);
  }
}

How do I accomplish this? 我该如何完成?

If you want flat array, use this.options['data']['columns'].push(...new_array[i]); 如果需要平面数组,请使用this.options['data']['columns'].push(...new_array[i]); instead of this.options['data']['columns'].push(new_array[i]); 而不是this.options['data']['columns'].push(new_array[i]);

or use this.options['data']['columns'] = this.options['data']['columns'].concat(new_array[i]) 或使用this.options['data']['columns'] = this.options['data']['columns'].concat(new_array[i])

Yes, and new_array should be an array, not object. 是的,并且new_array应该是一个数组,而不是对象。

You could do it using spread operator : 您可以使用传播运算符

 const options = { data: { columns: [] } }; const new_array = [ ["test1", 2, 3, 5, 6], ["test2", 5, 3, 9, 6], ["test3", 1, 2, 5, 2] ]; function populateColumn(array) { options.data.columns = [...array]; } populateColumn(new_array); console.log('options.data.columns:', options.data.columns); 

You seem to have an invalid object, you might want to update new_array from 您似乎有一个无效的对象,您可能想从以下位置更新new_array

let new_array = {['test1', 2,3,5,6], ['test2', 5,3,9,6], ['test3', 1,2,5,2]}

to

let new_array = [['test1', 2,3,5,6], ['test2', 5,3,9,6], ['test3', 1,2,5,2]]

Working demo: https://stackblitz.com/edit/angular-qjwfcq 工作演示: https//stackblitz.com/edit/angular-qjwfcq

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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