简体   繁体   中英

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]); instead of this.options['data']['columns'].push(new_array[i]);

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

Yes, and new_array should be an array, not object.

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

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

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