如何有条件地解构对象?

Kev*_*vvv 1 javascript destructuring ecmascript-6 reactjs

我有以下解构:

const {
    user: {
        username,
        image,
        uid
    } = {},
    gallery: {
        image: picture,
    } = {},
} = data
Run Code Online (Sandbox Code Playgroud)

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

因此,我得到:

null 不是对象

的错误消息gallery.image

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

Hao*_* Wu 5

回退仅在值是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);
Run Code Online (Sandbox Code Playgroud)

  • 但这不会:

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);
Run Code Online (Sandbox Code Playgroud)


所以,你可以手动从创建一个回退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);
Run Code Online (Sandbox Code Playgroud)