我有以下破坏:
const {
user: {
username,
image,
uid
} = {},
gallery: {
image: picture,
} = {},
} = data
问题是gallery
有时是null
(不是picture
中的gallery
),即使我需要的是picture
中的gallery
存在。换句话说,gallery: null
,而不是gallery.image: null
。
因此,我得到:
null不是对象
gallery.image
的错误消息。
我如何有条件地进行解构,以便在存在gallery.image
时使用它,但在空时gallery
不被解构?
Fallbacks仅适用于值为undefined
,但不适用于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
到{}
的后备: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);