Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Split array into individual variables

Considering this data structure:

var vehicles = [
  [ "2011","Honda","Accord" ],
  [ "2010","Honda","Accord" ],
  .....
];

Looping through each vehicles item, is there a way to reassign the array elements to individual variables all in one shot, something like:

for (i = 0; i < vehicles.length; i++) {
  var(year,make,model) = vehicles[i]; // doesn't work
  .....
}

... I'm trying to get away from doing:

for (i = 0; i < vehicles.length; i++) {
  var year = vehicles[i][0];
  var make = vehicles[i][1];
  var model = vehicles[i][2];
  .....
}

Just curious since this type of thing is available in other programming languages. Thanks!

like image 697
Wick Avatar asked Dec 21 '22 19:12

Wick


1 Answers

Now it is possible using ES6's Array Destructuring.

As from Docs:

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Consider the following example:

let [a, b, c] = [10, 20, 30];

console.log(a);  // output => 10
console.log(b);  // output => 20
console.log(c);  // output => 30

As with your data, .forEach() method can also be used for iterating over array elements along with Array Destructuring:

let vehicles = [
  [ "2011","Honda","Accord" ],
  [ "2010","Honda","Accord" ]
];

vehicles.forEach(([year, make, model], index) => {
  // ... your code here ...
  console.log(`${year}, ${make}, ${model}, ${index}`);
});

References:

  • Array Destructuring
  • Array.prototype.forEach()
  • Arrow Functions
  • Template Literals
like image 195
Mohammad Usman Avatar answered Jan 04 '23 07:01

Mohammad Usman