如何有条件地破坏物体?

问题描述 投票:0回答:1

我有以下破坏:

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不被解构?

javascript reactjs ecmascript-6 destructuring
1个回答
2
投票

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);
© www.soinside.com 2019 - 2024. All rights reserved.