when destructuring object in js & it has some value which is null then destructuring is failing with error Cannot read property 'id' of null
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. 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.
The default value in destructuring will only work for undefined properties and not null
From MDN
A variable can be assigned a default, in the case that the value unpacked from the object is undefined
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:
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.
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);