Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructing a javascript object to get inner object

I'm using the following code to get object from react state.

const { organizations } = this.state;

The sate object is as following.

this.state = {
    userOrganizations: {},
    OrganizationUsers: {}
}

userOrganizations is actually an object with an inner object named organizations. How can I map this using es6 code?

Edit

What I actually need is to get inner objects of both the userOrganizations and OrganizationUsers using the following code.

const { organizations, users } = this.state;

The organizations and users are sub objects which are inside the userOrganizations and OrganizationUsers.

So when I want to handle them, will they work with just calling

const { organizations, users } = this.state.userOrganizations, this.state.OrganizationUsers;
like image 321
Imesh Chandrasiri Avatar asked Feb 21 '26 00:02

Imesh Chandrasiri


2 Answers

You can nest destructruring like

const { userOrganizations : { organizations } } = this.state;

or simply write

const {  organizations  } = this.state.userOrganizations;
like image 103
Shubham Khatri Avatar answered Feb 23 '26 13:02

Shubham Khatri


This is so simple but still many got it wrong. Here is an example of inner destructuring

const obj = {
    someArray: [ 1, 2, 3],
    someInnerObj : {num: 123, txt: 'text'}
}

const {someArray: [first,second], someInnerObj: { num: myNum, txt: meText}} = obj
console.log(first,second,myNum,meText)

Try it in console

like image 38
Moti Korets Avatar answered Feb 23 '26 13:02

Moti Korets



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!