I have the following destructuring:
const {
user: {
username,
image,
uid
} = {},
gallery: {
image: picture,
} = {},
} = data
The problem is gallery
is sometimes null
(not the picture
within gallery
), even though what I need is the picture
within gallery
when it exists. In other words, gallery: null
, not gallery.image: null
.
Therefore, I get:
null is not an object
error message for gallery.image
.
How do I conditionally destructure so that gallery.image
is used when it exists, but gallery
isn't destructured when null?
I have the following destructuring:
const {
user: {
username,
image,
uid
} = {},
gallery: {
image: picture,
} = {},
} = data
The problem is gallery
is sometimes null
(not the picture
within gallery
), even though what I need is the picture
within gallery
when it exists. In other words, gallery: null
, not gallery.image: null
.
Therefore, I get:
null is not an object
error message for gallery.image
.
How do I conditionally destructure so that gallery.image
is used when it exists, but gallery
isn't destructured when null?
1 Answer
Reset to default 17Fallbacks only work when the value is undefined
but not null
- This will work:
const data = {
user: {
username: 'Alice',
image: 'alice.png',
uid: 1
},
gallery: undefined
};
const {
user: {
username,
image,
uid
} = {},
gallery: {
image: picture,
} = {},
} = data;
console.log(username, image, uid, picture);
- But this won't:
const data = {
user: {
username: 'Alice',
image: 'alice.png',
uid: 1
},
gallery: null
};
const {
user: {
username,
image,
uid
} = {},
gallery: {
image: picture,
} = {},
} = data;
console.log(username, image, uid, picture);
So, you can manually create a fallback from null
to {}
before you destructing it like this:
const data = {
user: {
username: 'Alice',
image: 'alice.png',
uid: 1
},
gallery: null
};
const {
user: {
username,
image,
uid
} = {},
gallery: {
image: picture,
}
} = {...data, gallery: data.gallery || {}};
console.log(username, image, uid, picture);
{}
as the fallback value as well for 'gallery', but I'm still getting thenull is not an object
error – Kevvv Commented Mar 4, 2020 at 2:49undefined
. Since it looks like it'snull
in your case, default value are useless. – Emile Bergeron Commented Mar 4, 2020 at 3:13