CodeBlanks Logo Icon CodeBlanks

Nested destructuring

JavaScript course · Advanced · Lesson 28/100

Learn to extract deeply nested properties.

Nested destructuring

You can also pull a property of an object that lives inside another object. You write a nested pattern: const { address: { city } } = user. Here the value of user.address.city goes into the city variable.

No address variable is created; only the inner city. The pattern must match the object's shape exactly; otherwise the value becomes undefined.

Mixing object and array patterns

In nested patterns you can mix object and array patterns. Writing const { items: [first] } = order takes order.items as an array and pulls its first element into first.

Again, no items variable is created; only first. This pattern is handy for grabbing the first item from API responses. Avoid going too deep; two levels are usually enough.

Exercise Extract order details

Create an order object with a customer (an object holding a name property) and an items array (at least one item). Use nested destructuring to pull customer.name into a name variable and the first element of items into first. Then log each one separately with console.log.

Show example solution
const order = {
  customer: { name: "Alex" },
  items: ["Pen", "Notebook"]
};
const { customer: { name }, items: [first] } = order;
console.log(name);
console.log(first);

Test yourself

  1. What does `const { address: { city } } = user` do?

    • Creates two variables: `address` and `city`
    • Creates only the `city` variable
    • Creates only the `address` variable
    • Throws because nesting is not allowed
    Show answer

    Creates only the `city` variable — Correct. The outer `address` is only used as a path; no variable is made.

  2. Complete the nested pattern

    const account = { profile: { name: "Alex" } };
    const { profile: { ____ } } = account;
    console.log(name);
    Show answer
    const account = { profile: { name: "Alex" } };
    const { profile: { name } } = account;
    console.log(name);
  3. Which assigns `order.items[0]` to the `first` variable?

    • `const { items[0]: first } = order`
    • `const [items: first] = order`
    • `const { items: first } = order`
    • `const { items: [first] } = order`
    Show answer

    `const { items: [first] } = order` — Correct. Since `items` is an array, a square-bracket pattern is applied.

  4. Match the concepts

    nested pattern
    Pulls a deep property in one step
    outer name
    Used only as a path, no variable
    mismatched pattern
    Result becomes undefined

All lessons in Advanced