如何使用默认值解构具有空值的嵌套对象 [英] How to destructure nested object with null value using default value

查看:33
本文介绍了如何使用默认值解构具有空值的嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当尝试分解可能为null的嵌套对象时,未使用默认值.

When trying to destructure a nested object which could be null, the default value is not being used.

我已经通过多个阶段的分解实现了这一目标,但如果可能的话,宁愿在单个阶段中完成.

I have accomplished this by destructuring in multiple stages, but would rather do it in a single stage if possible.

const obj = { a: null };
const { a: { b, c } = {} } = obj;

这将导致错误:
无法解构'undefined'或'null'的属性'b'

我希望b和c是 undefined

推荐答案

对于

For the default value to be used, the value which you are destructuring must be undefined.

const obj = { a: undefined };
const { a: { b, c } = {} } = obj;

console.log(b, c)

这篇关于如何使用默认值解构具有空值的嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆