Imesh Chandrasiri
Imesh Chandrasiri

Reputation: 5679

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;

Upvotes: 3

Views: 66

Answers (4)

CertainPerformance
CertainPerformance

Reputation: 370789

Just use dot notation until you get to the parent object just above the property you want

const obj = { outer: { inner: 'value' }};
const { inner } = obj.outer;
console.log(inner);

To destructure more than one thing at a time in different nested levels, try something like:

const x = {
  state: {
    userOrganizations: {
      organizations: 'orgValue'
    },
    OrganizationUsers: {
      users: 'userValue'
    }
  }
}
const { userOrganizations: { organizations }, OrganizationUsers: { users } } = x.state;
console.log(organizations + ' ' + users);

Upvotes: 1

Moti Korets
Moti Korets

Reputation: 3748

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

Upvotes: 1

Shubham Khatri
Shubham Khatri

Reputation: 281736

You can nest destructruring like

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

or simply write

const {  organizations  } = this.state.userOrganizations;

Upvotes: 3

Saravanan I
Saravanan I

Reputation: 1229

If i'am not wrong this should solve your issue,

const { organizations } = this.state.userOrganizations;

Upvotes: 0

Related Questions