如何有条件地解构对象?

How to conditionally destructure on object?

我有以下解构:

const {
    user: {
        username,
        image,
        uid
    } = {},
    gallery: {
        image: picture,
    } = {},
} = data

问题是 gallery 有时是 null(不是 gallery 中的 picture),即使我需要的是 picture gallery 当它存在时。换句话说,gallery: null,而不是gallery.image: null

因此,我得到:

null is not an object

gallery.image 的错误消息。

如何有条件地解构以便 gallery.image 在存在时使用,但 gallery 在 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{} 的回退:

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);