问题
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