Search code examples
javascriptobjectecmascript-6destructuring

Nested Object destructuring


When destructuring objects, I sometimes run into the issue of not knowing whether or not keys exist, and then trying to pull values from them. This obviously errors, since they are undefined. For example:

Expecting something like this:

{ user: { name: { first: 'Trey', last: 'Hakanson' } } }

But I actually get this:

{ user: {} }

and attempting to destructure like this errors:

const { user: { name: { first: firstName, last: lastName } } } = data

is there any way to assign a default value earlier in the deconstruction? Such as assigning name = { first: 'Hello', last: 'World' } if the name key doesn't exist?


Solution

  • const { user: { name: { first: firstName = 'firstName', last: lastName = 'lastName' } = {} } = {} } = data