Nested Object Destructuring in JavaScript

By Hemanta Sundaray on 2022-07-31

Here we have a JavaScript object:

const data = {
  categories: {
    group: [
      { id: 1, brand: "Ford" },
      { id: 2, brand: "GM" },
    ],
  },
}

We can unpack the group property from the data object, as shown below:

const {
  categories: { group },
} = data

console.log(group)
// [ { id: 1, brand: 'Ford' }, { id: 2, brand: 'GM' } ]

We can also unpack the group property from the data object and assign it to a variable with a different name:

const {
  categories: { group: brands },
} = data

console.log(brands)
// [ { id: 1, brand: 'Ford' }, { id: 2, brand: 'GM' } ]

Join the Newsletter