DEV Community

Cover image for JS Object Destructuring
Syed Kamal
Syed Kamal

Posted on

JS Object Destructuring

Destructuring object is very needful thing when you are working with objects in vanilla js or any other js frontend framework ,
lets destructe this object Destructuring ;)

let personalData = {
userId: 2223 ,
userDetail:{
    name :{
    userName :{
        fullName:{
            firstName:"John",
            lastName:"Bob",
            otherName: {
                nickName:"Jonn"
            }
        }
    },
    age: 24
    }
}
}

now if you want to have userId initialize in new variable you have to use dot notation to get the userId from personalData object.

let userIdofUser = personalData.userId;
userIdofUser; // output 2223

but now we have more simpler syntax for this using just curly braces containing exact key name of whatever key you required to initialize.

let {userId} = personalData;
userId; // output 2223

this way you got variable userId of personalData easily initialize in new variable, you can also rename the userId with the desired variable name whatever you want eg: idofUser1 separated by a colon with the key name

let {userId : idofUser1} = personalData;
idofUser1; // output 2223

Destructure whatever level you want , for suppose you want nickName directly initialize to some variable user1NickName you can do it too obvious

let {userDetail:{name : {userName : {fullName: {otherName : {nickName : user1NickName }  } } }}}= personalData; 
user1NickName ;

now user1NickName have that value "Jonn" ;)

Top comments (0)