alexmngn alexmngn - 1 month ago 23
Javascript Question

Conditional assignment and ECMAScript proposed object spread syntax

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

Answer

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.