Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Object destructuring: Assign null values in one line

Assuming I have an object like this

foo = {
    a: 1,
    b: 2,
    c: 3
};

I would destructure it this way

const {a, b, c} = foo;

However, what, if the keys a, b and c do not exist?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

foo = null;

This won’t work then

const {a, b, c} = foo;

I would have to do something like

let a, b, c;

if(foo) {
    a = foo.a;
    b = foo.b;
    c = foo.c;
};

Is there a way to do this in one line? Something like

 const {a, b, c} = foo ? foo : null; // this is not working

null is not an object. (evaluating ‘_ref2.a’)

>Solution :

When foo is not an object, you are going to have to give it an object so the destructuring can happen. So set it to an empty object using an ‘or’. Now if foo is defined it will use foo, if it is not defined it will use the default object.

const foo = undefined;
const { a, b, c } = foo || {};
console.log(a, b, c);

If you want default values, set them in the object.

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

If you want default values if the object does not provide them all, you can set values in the destructuring.

const foo = { a: 1};
const { a = "a", b = "b", c = "c" } = foo || {};
console.log(a, b, c);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading