简体   繁体   English

javascript object 用空值或可空键解构一行

[英]javascript object destructuring one line with nulls or nullable keys

when destructuring object in js & it has some value which is null then destructuring is failing with error Cannot read property 'id' of null当在 js 中解构 object 并且它有一些值是 null 然后解构失败并出现错误无法读取 null 的属性“id”

 const abc = {a: 1, b: 2, c: null}; let {c = {}, c: {id} = {}} = abc || {}; console.log('c, id', c, id);

in case value of a key is null, js throws an exception.如果key的值为null,js会抛出异常。 we dont know which key is nullable.我们不知道哪个键可以为空。 I want this to be handled in a single line like normal destructuring.我希望像正常解构一样在一行中处理它。 is it possible.可能吗。 for this example sake, make into two lines first check if c is null but I want to do it one line.对于这个例子,首先检查 c 是否为 null 分为两行,但我想做一行。

The default value in destructuring will only work for undefined properties and not null解构中的默认值仅适用于undefined的属性,不适null

From MDN来自MDN

A variable can be assigned a default, in the case that the value unpacked from the object is undefined如果从 object 解压缩的值未定义,则可以为变量分配默认值

 const abc = {a: 1, b: 2, c: undefined}; let {c = {}, c: {id} = {}} = abc || {}; console.log('c, id', c, id);

For c: null , you'd have to use:对于c: null ,您必须使用:

let id = abc.c?.id

Not the best way to do but, I have got an idea to convert nulls to undefined before destructuring so that, js will take care of taking the default values.不是最好的方法,但是,我有一个想法,在解构之前将空值转换为未定义,这样 js 将负责采用默认值。

here is the working code这是工作代码

 function removeNulls(obj) { if (obj === null) { return undefined; } if (typeof obj === 'object') { for (let key in obj) { obj[key] = removeNulls(obj[key]); } } return obj; } const abc = {a: 1, b: 2, c: null}; let {c = {}, c: {id, id2} = {}} = removeNulls(abc) || {}; console.log('c, id, id2:', c, id, id2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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