James
James

Reputation: 13

Is it possible to push to an array the same time as I add an object?

I'd like to push a value to an array the same time I add an object to it. Is this possible? Here is a short demo of my code:

let abc = [
  [],
  {}
];

$('form').find('input').each(function() {
  // This works but I'd like to do it in one step if possible
  abc[0].push(this);
  abc[1][this.name] = 'Text';

  // I'd like to change it to something like this
  abc = [
    this,
    this.name: 'Text'
  ];
)};

Upvotes: 1

Views: 64

Answers (1)

James McGuigan
James McGuigan

Reputation: 8106

For this you need the ES6 spread operator

abc = [
  [ ...abc[0], this ],
  { ...abc[1], [this.name]: 'Text' },
  ...abc.slice(2)
];

More information can be found here

Upvotes: 5

Related Questions