[英]How to conditionally destructure on object?
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.问题是gallery
有时为null
(不是gallery
的picture
),即使我需要的是gallery
存在的picture
。 In other words, gallery: null
, not gallery.image: null
.换句话说, gallery: null
,而不是gallery.image: null
。
Therefore, I get:因此,我得到:
null is not an object null 不是对象
error message for gallery.image
. gallery.image
错误消息。
How do I conditionally destructure so that gallery.image
is used when it exists, but gallery
isn't destructured when null?我如何有条件地解构,以便在存在时使用gallery.image
,但在为 null 时不解构gallery
?
Fallbacks only work when the value is undefined
but not null
回退仅在值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
to {}
before you destructing it like this:因此,您可以在像这样销毁它之前手动创建从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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.