Skip to content
Advertisement

JavaScript: Split array into individual variables

Considering this data structure:

JavaScript

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

JavaScript

… I’m trying to get away from doing:

JavaScript

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

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

JavaScript

References:

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement