Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 935
alexmngn Avatar asked Nov 25 '25 10:11

alexmngn


1 Answers

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.

like image 157
loganfsmyth Avatar answered Nov 28 '25 00:11

loganfsmyth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!