2

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

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the answer, I understand better now. If you check my example though, node.Menu.Item is an array. How do I destructure an array property of an object?
What part of the array do you need, the object within the array or the ItemId property of that object?
Thank you, I need the object within the array.
Excellent, thank you very much for making this so clear to me.
@rm-rf no problem amigo, glad to help out :)
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.