Destructuring allows you to extract individual values from an array into variables or constants:
let users = ["Alexander", "Axel", "Artur"]; let [a, b, c] = users;//we indicate in turn which element of the array, which value of the variable to assign console.log(a);// Alexander console.log(b);// Alex console.log(c);//Artur
If there are fewer variables/constants than array elements, then the remaining array elements are simply omitted.
If there are more variables/constants than array elements, then unmatched variables/constants get the value undefined.
Getting the remaining elements of an array into another array
With the … operator, you can get all the remaining elements of an array as another array:
let users = ["Tom", "Sam", "Bob", "Mike"]; let [tom, ...others] = users; console.log(tom); // Tom console.log(others); // ["Sam", "Bob", "Mike"]
Here, the others array will contain the last three elements of the array.
Skip elements
We can skip a number of array elements, leaving gaps instead of variable names:
let users = ["Tom", "Sam", "Bob", "Ann", "Alice", "Kate"]; let [first, , , , fifth] = users; console.log(first); // Tom console.log(fifth); // Alice
Destructuring objects from arrays
You can combine getting data from an array and an object:
let people = [ { name: "Tom", age: 34 }, { name: "Bob", age: 23 }, { name: "Sam", age: 32 } ]; let [, { name }] = people; console.log(name);//Bob
Objects destructuring in JavaScript. Code examples
August 15, 2022