rm-rf rm-rf - 1 month ago 16
Javascript Question

Nested Destructuring on Object Assignments

With ES6 destructuring, is their any way to destructure nested objects on assignment?

Here is a quick code example to show what I mean:

let node = {
ItemTitle: 'Title',
ItemId: 5,
Menu: {Item: [{ItemId: 579}]
}

// my attempts
let {
ItemId: id,
ItemTitle: title,
Menu['Item']: subItems
} = node

let {
ItemId: id,
ItemTitle: title,
Menu.Item: subItems
} = node

Answer

You can just repeat the same syntax for nested levels as with destructuring the top level:

EDIT based on your comment

I need the object within the array

let node = {
  ItemTitle: 'Title',
  ItemId: 5,
  Menu: {Item: [{ItemId: 579}]}
}

let {
  ItemId: id,       // extract `node.ItemId` into a variable called `id`
  ItemTitle: title, // extract `node.ItemTitle` into a variable called `title`
  Menu: {
    Item: [obj]     // extract `node.Menu.Item[0]` into a variable called obj
  }
} = node;

console.log('id =', id);
console.log('title =', title);
console.log('obj =', obj);

Pre-edit: Extracting the id of the object within the nested array.

let node = {
  ItemTitle: 'Title',
  ItemId: 5,
  Menu: {Item: [{ItemId: 579}]}
}

let {
  ItemId: id,           // extract `node.ItemId` into a variable called `id`
  ItemTitle: title,     // extract `node.ItemTitle` into a variable called `title`
  Menu: {
    Item: [{ 
      ItemId: subItemId // extract `node.Menu.Item[0].ItemId` into a variable called `subItemId`
    }]  
  }
} = node;

console.log('id =', id);
console.log('title =', title);
console.log('subItemId =', subItemId);