嵌套对象解构 [英] 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:
期待这样的事情:
{ user: { name: { first: 'Trey', last: 'Hakanson' } } }
但是我实际上得到了:
{ user: {} }
并尝试破坏此类错误:
const { user: { name: { first: firstName, last: lastName } } } = data
在解构之前,有什么方法可以分配默认值吗?例如如果name
键不存在则分配name = { first: 'Hello', last: 'World' }
?
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
这篇关于嵌套对象解构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文