Destructuring Nested Objects in JavaScript

Destructuring nested objects in JavaScript is a handy trick. It's a technique that allows you to extract specific pieces of data from deeply nested objects. Here's how you can do it:

The syntax for destructuring nested objects is straightforward:

const user = {
    name: "Niall",
    age: 32,
    address: {
        city: "New York",
        country: "USA"
    }
};

// Destructuring nested objects
const { name, address: { city, country } } = user;

console.log(name);   // Output: John
console.log(city);   // Output: New York
console.log(country);// Output: USA

By specifying the object's structure within curly braces, including any nested properties, you can extract the desired values in a single line of code.

JavaScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.