简体   繁体   English

如何使用默认值使用null值来构造嵌套对象

[英]How to destructure nested object with null value using default value

When trying to destructure a nested object which could be null, the default value is not being used. 尝试构造可能为null的嵌套对象时,不使用默认值。

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;

This results in error: 这会导致错误:
Cannot destructure property 'b' of 'undefined' or 'null'

I would expect b and c to be undefined 我希望b和c是undefined

For the default value to be used, the value which you are destructuring must be undefined . 对于要使用的默认值 ,必须undefined要解构的值。

 const obj = { a: undefined }; const { a: { b, c } = {} } = obj; console.log(b, c) 

You can change null to empty object in a temporary object. 您可以将null更改为临时对象中的空对象。 Using map() on entries of object change null to empty object {} and then convert it to object using Object.fromEntries 在对象条目上使用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) 

Your code looks like this after transpiling : 转换后,您的代码如下所示

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;

Here _obj$a is the temporary variable referencing obj.a . 这里_obj$a是引用obj.a的临时变量。 If a default value is provided, it will only check this value against void 0 (or undefined ) and not against null 如果提供了默认值,它将仅针对void 0 (或undefined )检查此值,而不是针对null

You can still do this using destructuring. 你仍然可以使用解构做到这一点。 But, a traditional null and undefined check is much easier to understand. 但是,传统的nullundefined检查更容易理解。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM