Kevvv
Kevvv

Reputation: 4023

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. In other words, gallery: null, not gallery.image: null.

Therefore, I get:

null is not an object

error message for gallery.image.

How do I conditionally destructure so that gallery.image is used when it exists, but gallery isn't destructured when null?

Upvotes: 5

Views: 12663

Answers (1)

Hao Wu
Hao Wu

Reputation: 20669

Fallbacks only work when the value is undefined but not 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:

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

Upvotes: 17

Related Questions