JavaScript - adding properties to an object using the spread syntax within a ternary statement

Viewed 1792

I want to conditionally append different headers to my request object. I don't want to use if/else.

The following ... gives syntax error expression expected.

I've looked at some other examples on SO but they don't seem to work. I just can't get my syntax right.

headers is some object that comes from function args which may or may not exist.

What is the correct way to write this?

    const req = {
      meta: {
        id: "asd123"
      }
    }

    {...req.meta, ...( headers ? headers : { "Content-Type": "application-json" })}

I want my output to look something like this

    const req = {
      meta: {
        id: "asd123"
      }
      headers: {
        ContentType: "application-json",
      }
    }
5 Answers

You need req as complete object for spreading and a new headers property.

result = { ...req, headers: (headers || { "Content-Type": "application-json" }) };

If you like to use short hand properties, you need to update headers first.

headers = headers || { "Content-Type": "application-json" };
result = { ...req, headers };

If you just typed this line

{...req.meta, ...( headers ? headers : { "Content-Type": "application-json" })}

Into your IDE, this is not an expression. You should assign it to a variable or use it in another way. The ternary part seems fine to me.

Probably

{...req, headers: headers || { "Content-Type": "application-json" }}

req.headers will be assigned to headers if it exists or { "Content-Type": "application-json" } if not.

As header is coming as a funtion's args - you can first default initialize that header with undefined. Then just try this code -

if header is present then simply destructure it - {...req.meta, ...( headers ? {headers} : { "Content-Type": "application-json" })}

Code Readability has its own importance. Thus, I find below solution as most appropiate:

req.headers = headers || { "Content-Type": "application-json" }

Also, You can use Nullish coalescing operator '??' as below :

req.headers = headers ?? { "Content-Type": "application-json" }

But, '??' is a recent addition to the language. Old browsers may need polyfills.

Related