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?
const { user: { name: { first: firstName = 'firstName', last: lastName = 'lastName' } = {} } = {} } = data
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With