16

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

5
  • 2
    the default value is not being used what default values? Commented May 13, 2019 at 8:57
  • 1
    How can you destructure something that does not exist? You would have to set the object to be intialized const obj = { a: { b, c} } Commented May 13, 2019 at 8:58
  • @AZ_ The default value is denoted by = {} on the second line of code. So, if a is undefined, an empty object will be destructured instead. Commented May 13, 2019 at 9:32
  • @Michael That is the purpose of the = {}. So if a is undefined, an empty object will be used for the purpose of the destructuring. Commented May 13, 2019 at 9:36
  • Ok, default value only assigned if the property does not exist(undefined). Commented Sep 10, 2021 at 14:42

4 Answers 4

19

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)

Sign up to request clarification or add additional context in comments.

1 Comment

But if a is null instead of undefined, this doesn't work.
0

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)

Comments

-1

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;
}

Comments

-1

You can use destructuring twice and get the required output -

const { a = {} } = { a: null }
const { b = '', c = '' } = a || {}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.