DEV Community

Cover image for JavaScript nested object destructuring
Shakil Khan
Shakil Khan

Posted on

JavaScript nested object destructuring

Objects are commonly used in JavaScript, if you are a React, Vue, or Angular developer then you may have a good relation with objects because they are heavily used in those frameworks, in this article I will show you how you can use JavaScript object efficiently.

const info = {
name: "Shakil Khan",
email: "example@gmail.com",
address: {
country: {name: "Pakistan", religion:"Islam"},
line1: "Malakand Batkhela",
line2: "City Batkhela"
}
}
Enter fullscreen mode Exit fullscreen mode

in up code, as you can see we have a JavaScript object that has different keys name, email, address now inside the address we have a country key which also has a new object and it has two keys name and religion in simple words info object has nested objects, Now how we can access data from info object there are couple ways to access data from any JavaScript object.

const {name, email, address} = info;
const {country, line, line2} = address;
const {name, religion} = country;
Enter fullscreen mode Exit fullscreen mode

in up code, we have destructured keys from info object which are name, email, and address, and further, we destructed address object and finally, we have destructured country object that is fine but have a short way and that is below

const {name, email, address: {country: {name, religion}, line1, line2}} = info;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)