Monday, May 20, 2024
180
rated 0 times [  182] [ 2]  / answers: 1 / hits: 17349  / 6 Years ago, sat, june 23, 2018, 12:00:00

I understand this probably is a pretty basic question, but I'm not proficient with ES6 and I've encountered this syntax:



const { rootStore: { routerStore } } = this.props;


I understand what something like this means:



const { rootStore } = this.props;


(Creating a const rootStore from the property rootStore in this.props).



But what does the above double deconstruction (I assume it's deconstruction) mean?


More From » ecmascript-6

 Answers
3

This is called nested destructuring, and it's very useful in many situations.


Let's understand it bit by bit.


Look at this example:




const person = {
friend: {
name: 'john',
age: 20,
},
};

const { friend } = person;

console.log(friend);




Here we get the value of the prop friend using destructuring. Since the value itself is an object, we can use destructuring with it as well.


From the previous example:




const person = {
friend: {
name: 'john',
age: 20,
},
};

const { friend } = person;

console.log(friend);

const {age} = friend ;

console.log(age) ;




Now we get the age prop using destructuring as well, and that's pretty and super handy, but what if I just need the age prop and I don't need the friend prop? Can I do all the above example in one step? Yes!! and that's the awesomeness of ES6:




const person = {
friend: {
name: 'john',
age: 20,
},
};

const { friend :{age} } = person;

console.log(age);




As you can see, we get the value of age in one step, and that's useful in many situations when you have nested objects. In the code above, if you try to log the value of friend you'll get ReferenceError: friend is not defined.


Did you know? You can make nested destructuring as deep as you want. Look at this complex example which is just for fun.




const person = {
friend: {
name: 'john',
other: {
friend: {
name: {
fullName: {
firstName: 'demo',
},
},
},
},
},
};

const {
friend: {
other: {
friend: {
name: {
fullName: { firstName },
},
},
},
},
} = person;

console.log(firstName); // demo




Pretty!!


If you want to know more about destructuring take a look at these resources:


Destructuring assignment MDN


Destructuring and parameter handling in ECMAScript 6


[#54133] Wednesday, June 20, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
frankiefredyr

Total Points: 555
Total Questions: 108
Total Answers: 94

Location: Egypt
Member since Tue, May 3, 2022
2 Years ago
;