简体   繁体   English

如何有条件地解构对象?

[英]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 (不是gallerypicture ),即使我需要的是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

  • 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:因此,您可以在像这样销毁它之前手动创建从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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM