Nested Object destructuring [duplicate]

天大地大妈咪最大 提交于 2019-12-07 09:00:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!