Steve
Steve

Reputation: 41

Destructuring nested object having null value cause "TypeError: cannot read property 'obj2' of null"

I try destructuring nested object having null value, but it cause "TypeError: cannot read property 'obj2' of null".

I read about fixing it, but it works on not nested elements.

Take a look at code snippet.

const tmp = { obj: null };

let { obj: { obj2 } = {} } = tmp || {};

I expect destructure object and obj2 to be null or undefined, but it cause error :(

It works good when I have "undefined" instead of "null", but I need case with "null".

Upvotes: 3

Views: 2149

Answers (3)

Steve
Steve

Reputation: 41

Thanks guys @Dez @junvar

I change my code to sth like:

const tmp = { obj: null };
const obj2 = tmp?.obj?.obj2;
console.log(obj2);

Upvotes: 0

Dez
Dez

Reputation: 5838

ES6 destructuring default values only work if the attribute is undefined. In any other case it will get the value passed assigned. Even the Javascript falsy values.

A way to circumvent that is to shortcut the possible falsy values, in this case obj that is going to be null.

const tmp = { obj: null };

const { obj } = tmp;

const { obj2 = {} } = obj || {};

console.log(obj);
console.log(obj2);

 

Upvotes: 3

junvar
junvar

Reputation: 11574

You won't be able to do that with destructuring. Simply put, like deafult functin parameters, default destructuring values are only applied if the value is undefined, not null or other falsey values.

As an alternative, you could do:

const tmp = { obj: null };
let obj2 = tmp && tmp.obj && tmp.obj.obj2;

Upvotes: 0

Related Questions