DEV Community

Cover image for JS Object Destructuring
Syed Kamal
Syed Kamal

Posted on

4

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" ;)

Heroku

Amplify your impact where it matters most — building exceptional apps.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay