Reputation: 1372
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;
This results in error:
Cannot destructure property 'b' of 'undefined' or 'null'
I would expect b and c to be undefined
Upvotes: 16
Views: 12107
Reputation: 1
You can use destructuring twice and get the required output -
const { a = {} } = { a: null }
const { b = '', c = '' } = a || {}
Upvotes: -1
Reputation: 386654
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)
Upvotes: 19
Reputation: 35232
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
. If a default value is provided, it will only check this value against void 0
(or undefined
) and not against null
You can still do this using destructuring. But, a traditional null
and undefined
check is much easier to understand.
let obj = { a: null },
a = obj.a,
b, c;
if (typeof a !== "undefined" && a !== null) {
b = obj.a.b;
c = obj.a.b;
}
Upvotes: -1
Reputation: 36574
You can change null
to empty object in a temporary object. Using map()
on entries of object change null
to empty object {}
and then convert it to object using 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)
Upvotes: 0