【问题标题】:How to conditionally destructure on object?如何有条件地解构对象?
【发布时间】:2020-06-16 11:45:16
【问题描述】:

我有以下解构:

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

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

因此,我得到:

null 不是对象

gallery.image 的错误消息。

如何有条件地解构以便gallery.image 在存在时使用,但gallery 在为空时不解构?

【问题讨论】:

标签: javascript reactjs ecmascript-6 destructuring


【解决方案1】:

仅当值为 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);

【讨论】:

  • 谢谢你。你能解释一下这部分gallery: data.gallery吗?
  • 它是gallery: data.gallery || {}。默认情况下,gallery 属性从 data.gallery 获取值。 data.gallery || {} 表示如果data.gallery 是真值,则使用该值;如果它是一个虚假值 (null, undefined, 0, etc.) ,请改用 {}
  • 最后,来自data 的属性和经过处理的gallery 属性合并为一个对象并准备销毁。
  • 好的,我明白了。谢谢
猜你喜欢
  • 2019-05-13
  • 2019-04-06
  • 2021-06-16
  • 1970-01-01
  • 2020-08-28
  • 2020-10-20
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
相关资源
最近更新 更多