In this section, we will learn what the nested destructuring is and how to use it in JavaScript.
What is Nested Destructuring in JavaScript?
So far, we’ve seen how to extract the values of an object or array from just the top level of the target array/object! Basically, so far there wasn’t any object that had a property with another object as its value. Or we didn’t have an array with another array as its element (AKA multidimensional array).
But destructuring syntax can go deeper and, in fact, we can extract the elements of sub-objects and sub-arrays using destructuring as well (which is known as Nested Destructuring). We do this the same way we create nested objects/ arrays in an object and array literals.
So let’s see them in practice now!
Example: destructuring nested objects in JavaScript
For example, let’s say we have this object:
const obj = { a:[1,2,3], b:[4,5,6] }
Now we want to get the first and the second elements of the array that are assigned to the `a` property.
Basically, the array is nested within an object.
This is how we can access and store these two elements into two variables:
const obj = { a:[1,2,3], b:[4,5,6] } const { a:[first, second] } = obj; console.log(first, second);
Output:
1 2
As you can see by putting the two identifiers `first` and `second` into a pair of brackets, we’re telling the execution engine that our interest is only on the first and the second elements of the returned array.
Now let’s say we have an object that each of its properties has another object as its value.
Example: Nested Object Destructuring in JavaScript
const obj = { first:{a:1, b:2}, second:{a:3, b:4} } const { first:{a:variable} } = obj; console.log(variable);
Output: 1
Here, we want to assign the value of the `a` property to the `variable` identifier. The `a` property is a property that belongs to the object that is assigned to the `first` property.
So here the engine in the destructor will return the object of the `first` property and after that we used a pair of braces and inside that specified that we’re only interested in the value of the `a` property of this returned object and want it to be assigned to the `variable` identifier.
Example: destructuring nested arrays in JavaScript
const list = [ {a:1, b:2}, {a:3, b:4} ] const [ {a:first},{b:second} ] = list; console.log(first, second);
Output:
1 4
Here, the `list` array has two elements and both of them are objects with two properties for each with the names `a` and `b`.
In the destructuring, we’re mentioning that for the first element, we’re only interested in the value of the `a` property and want it to be assigned to the `first` identifier.
Also, for the second element in the destructuring pattern, we’re pointing to the `b` property and want it to be assigned to the `second` identifier.
Reference book:
JavaScript the new Toys
Author: T.J. Crowder