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 es 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",
}
}
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 es 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",
}
}
Share
Improve this question
asked Jul 4, 2020 at 16:13
asusasus
1,7595 gold badges30 silver badges67 bronze badges
5 Answers
Reset to default 2You need req
as plete 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 ing 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.