Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 double destructure

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?

like image 566
Avi Avatar asked Jun 23 '18 09:06

Avi


2 Answers

This is called nested destructuring and its 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 and the value itself is an object and we can use destructring 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 deep nested destructuring 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 everything about destructuring look at this resources

Destructuring assignment MDN

Destructuring and parameter handling in ECMAScript 6

like image 181
mostafa tourad Avatar answered Sep 22 '22 09:09

mostafa tourad


It means

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

Except the first line will not effect, which is rootStore will not be defined.

like image 44
Rudy Huynh Avatar answered Sep 19 '22 09:09

Rudy Huynh