Considering this data structure:
JavaScript
x
6
1
var vehicles = [
2
[ "2011","Honda","Accord" ],
3
[ "2010","Honda","Accord" ],
4
..
5
];
6
Looping through each vehicles item, is there a way to reassign the array elements to individual variables all in one shot, something like:
JavaScript
1
5
1
for (i = 0; i < vehicles.length; i++) {
2
var(year,make,model) = vehicles[i]; // doesn't work
3
..
4
}
5
… I’m trying to get away from doing:
JavaScript
1
7
1
for (i = 0; i < vehicles.length; i++) {
2
var year = vehicles[i][0];
3
var make = vehicles[i][1];
4
var model = vehicles[i][2];
5
..
6
}
7
Just curious since this type of thing is available in other programming languages. Thanks!
Advertisement
Answer
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:
JavaScript
1
5
1
let [a, b, c] = [10, 20, 30];
2
3
console.log(a); // output => 10
4
console.log(b); // output => 20
5
console.log(c); // output => 30
As with your data, .forEach()
method can also be used for iterating over array elements along with Array Destructuring:
JavaScript
1
9
1
let vehicles = [
2
[ "2011","Honda","Accord" ],
3
[ "2010","Honda","Accord" ]
4
];
5
6
vehicles.forEach(([year, make, model], index) => {
7
// ... your code here ...
8
console.log(`${year}, ${make}, ${model}, ${index}`);
9
});
References: