Reputation: 4023
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?
Upvotes: 5
Views: 12663
Reputation: 20669
Fallbacks only work when the value is undefined
but not null
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);
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);
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);
Upvotes: 17