![](/img/trans.png)
[英]How to destructure an object by assigning default value when value is already null
[英]How to destructure nested object with null value using default value
尝试构造可能为null的嵌套对象时,不使用默认值。
我通过多个阶段的解构来完成这个,但如果可能的话,宁愿在一个阶段中完成。
const obj = { a: null };
const { a: { b, c } = {} } = obj;
这会导致错误:
Cannot destructure property 'b' of 'undefined' or 'null'
我希望b和c是undefined
对于要使用的默认值 ,必须undefined
要解构的值。
const obj = { a: undefined }; const { a: { b, c } = {} } = obj; console.log(b, c)
您可以将null
更改为临时对象中的空对象。 在对象条目上使用map()
将null
更改为空对象{}
,然后使用Object.fromEntries
将其转换为对象
const obj = { a: null }; const { a: { b, c } = {} } = Object.fromEntries(Object.entries(obj).map(x => x[1] === null ? {} : x)); console.log(b,c)
转换后,您的代码如下所示 :
var obj = { a: null };
var _obj$a = obj.a;
_obj$a = _obj$a === void 0 ? {} : _obj$a;
var b = _obj$a.b,
c = _obj$a.c;
这里_obj$a
是引用obj.a
的临时变量。 如果提供了默认值,它将仅针对void 0
(或undefined
)检查此值,而不是针对null
你仍然可以使用解构来做到这一点。 但是,传统的null
和undefined
检查更容易理解。
let obj = { a: null },
a = obj.a,
b, c;
if (typeof a !== "undefined" && a !== null) {
b = obj.a.b;
c = obj.a.b;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.