Let's say I have
const {status} = req.body;
I want to include status in my query object only if the status has truthy value(other than null
or undefined
or empty string),
Currently I'm doing this,
const query = {
otherCondition: 1,
};
if (status) {
query.status = status;
}
Is there any way to avoid this using if clause using ES6 Object shorthand ?
If I use,
const query = {
otherCondition: 1,
status,
}
When the status is undefined
, it generates
{
otherCondition: 1,
status: "undefined",
}
You can use object spread with short circuit evaluation:
...status && { status }
If status
is a falsy value, the evaluated expression won't "return" object, and spread will ignore it. If it's a truty value, the short circuit will "return" the { status }
object, and the spread will work in the normal way:
Falsy
const {status} = {};
const query = {
otherCondition: 1,
...status && { status }
};
console.log(query);
Truthy
const {status} = { status: 5 };
const query = {
otherCondition: 1,
...status && { status }
};
console.log(query);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With