3

I'm playing a bit with the assignment and proposed object spread syntax and I was wondering if there is a way to assign something only with a condition?

For example, I currently have the following:

const requestHeaders = { ...headers };

if (accessToken) {
    requestHeaders.Authorization = `Bearer ${accessToken}`;
}

const h = {
    Accept: 'application/json',
    ...requestHeaders,
},

And I wanted to simplify it with something like this:

const requestHeaders = {
    ...headers, {
        Authorization: accessToken ? `Bearer ${accessToken}` : void 0, // I don't want Authorization to appear in the object if it's null or undefined, but this doesn't work
    }
};

const h = {
    Accept: 'application/json',
    ...requestHeaders,
},

Is there any way to assign conditionally an attribute to an object?

Thanks

alexmngn
  • 9,107
  • 19
  • 70
  • 130
  • 4
    FYI, calling these things "ES7" is a misnomer, they are proposed syntax features. ES7 is done and published and they are not part of it. – loganfsmyth Nov 07 '16 at 06:02
  • They are also not "ES2017", they could land in any version of the spec, or never land in any version. They are just "syntax proposals". – loganfsmyth Nov 07 '16 at 06:04
  • 2
    [`...` is not an operator](http://stackoverflow.com/a/37152508/218196) – Felix Kling Nov 07 '16 at 06:35

1 Answers1

8

You could use this style

const requestHeaders = {
    ...headers,
    ...(accessToken ? {
        Authorization: `Bearer ${accessToken}`,
    } : {}),
};

where you either spread an object with the key you want, or an empty object.

loganfsmyth
  • 156,129
  • 30
  • 331
  • 251