Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 Javascript Shorthand create property only if it's truthy

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",
}
like image 317
Kamalakannan J Avatar asked Mar 05 '23 19:03

Kamalakannan J


1 Answers

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);
like image 112
Ori Drori Avatar answered Mar 09 '23 06:03

Ori Drori