Akash
Akash

Reputation: 988

Multilevel object Destructuring in ES6

If I have the below object,

const obj = {
   user:
   {
    type:{
      type1:"developer",
      type2:"architect"
    },
    role:"admin"
   },
   salary:50000
}

const {user: {type}} = obj;
console.log(`type:  ${type}`);
console.log(user);

and if I write something like below,

const {user: {type}} = obj;
console.log(type);  //prints [object Object] which is right

but if I try to print

console.log(user); // ReferenceError: user is not defined 

can someone please explain me the below syntex of ES6 destructuring?

const {user: {type}} = obj;

Upvotes: 2

Views: 234

Answers (1)

Jack Bashford
Jack Bashford

Reputation: 44107

Currently, what you're doing is you're taking the user sub-object, and extracting the type from it. It's easier if you think about it like a function - when you destructure out properties, the original object isn't saved anywhere and is no longer accessible. Same here - user isn't accessible anymore.

What you could do if you wanted to access it would be to extract type from user, and also extract user and keep it.

const obj = {
  user: {
    type: {
      type1: "developer",
      type2: "architect"
    },
    role: "admin"
  },
  salary: 50000
}

const { user: { type }, user } = obj;
console.log(`type:  ${type}`);
console.log(user);

Upvotes: 4

Related Questions