问题
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?
回答1:
const { user: { name: { first: firstName = 'firstName', last: lastName = 'lastName' } = {} } = {} } = data
回答2:
You can assign default values if the value is falsy value or undefined in your case. In javascript the default values can be assigned by using the || operator.
If the first operand is falsy (false, null, undefined, "",0) then it returns the second operand. Otherwise, it returns the first operand. This provides a convenient way to specify default values
var myDefaultName = name || { first: 'Hello', last: 'World' }
来源:https://stackoverflow.com/questions/41171421/nested-object-destructuring