Nested Destructuring on Object Assignments

时光怂恿深爱的人放手 提交于 2019-12-11 07:03:52

问题


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

回答1:


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);



回答2:


Yes, you can do nested destructuring with ES6. MDN gives you a nice example.

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

let { Menu: { Item: [{ ItemId }] } } = node

console.log(ItemId) // 579


来源:https://stackoverflow.com/questions/40429117/nested-destructuring-on-object-assignments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!