Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested Object destructuring [duplicate]

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?

like image 802
treyhakanson Avatar asked Mar 10 '23 09:03

treyhakanson


1 Answers

const { user: { name: { first: firstName = 'firstName', last: lastName = 'lastName' } = {} } = {} } = data
like image 116
Mayday Avatar answered Mar 20 '23 06:03

Mayday