简体   繁体   中英

Shorter way to write if statement with multiple OR conditions?

I am writing a function that inserts values into a database.

I am checking to make sure that all fields are filled out by the user before the form is submitted.

If not, a message is displayed saying to fill out all fields.

if (!req.query.itemCode || !req.query.itemCode || !req.query.totalQuantity || !req.query.availableQuantity || !req.query.quantityRequested || !req.query.requestor || !req.query.projectNum || !req.query.projectDetails) return 

You can see that with 5+ values, it quickly turns into a big if statement

Thanks

You can create a specific function that return a bool and call this function in your if statement, this is the proper way because if somewhere else you need to do the same check you will call the function and avoid code duplication. Plus you can iterate over the req.query to check Null values

for (var propName in req.query) {
    if (req.query.hasOwnProperty(propName)) {
        If (!req.query[propName]) { return false: }
    }
}

You could make a local reference to query to shorten it a tiny bit but ultimately that's pretty much the best way to do it. I might also divide it by line breaks for readability.

let query = req.query;

if (!query.itemCode 
    || !query.itemCode 
    || !query.totalQuantity 
    || !query.availableQuantity 
    || !query.quantityRequested 
    || !query.requestor 
    || !query.projectNum 
    || !query.projectDetails) 
return;

You could use a helper function that takes an array of names, and checks each of those:

 const exists = (obj, ...keys) => {
   for(const key of keys)
     if(!obj[key]) throw new Error(`$key} is missing!`);
 };

 exists(req, "itemCode", /*...*/)

I assume its inside a Express handler, in that case add an error route to then send the error to the client.

Or, you could even create a middleware:

 const exists = (...keys) => (req, res, next) => {
   for(const key of keys) {
      if(!req.query[key])
       return res.status(500).send(`${key} is missing`);
   }
   next(); // all fine, go on
};

app.get("/stuff", exists("itemCode", /*...*/), (req, res) => {
  //...
});

For those who may be new to using the rest parameter syntax:

The rest parameter syntax allows us to represent an indefinite number of arguments as an array.

function myFun(a, b, ...manyMoreArgs) {
  console.log("a", a); 
  console.log("b", b);
  console.log("manyMoreArgs", manyMoreArgs); 
}

myFun("one", "two", "three", "four", "five", "six");

// Console Output:
// a, one
// b, two
// manyMoreArgs, [three, four, five, six]

Given this syntax produces an array, we can then iterate over that with a for...of statement, eg:

function myFun(a, b, ...manyMoreArgs) {
  console.log("a", a); 
  console.log("b", b);
  for (let value of manyMoreArgs) {
    console.log(value);
  }
}

myFun("one", "two", "three", "four", "five", "six");

// Console Output:
// a, one
// b, two
// three
// four
// five
// six

You can easily write a little helper function for that. For example, you can hand over the object for which you want to make sure certain properties are set ( req.query in your case), plus a list of properties that need to be set.

 function areAllPropertiesSet(obj, props) { for (const prop of props) { if (!obj[prop]) { return false; } } return true; } const req = { query: { 'param1': 'bla', 'param2': 'blubb', 'param3': 'hi' } }; console.log(areAllPropertiesSet(req.query, ['param1', 'param2', 'param3']) === true); console.log(areAllPropertiesSet(req.query, ['param1', 'param2', 'param3', 'param4']) === false); 

You could use Object.values() on req.query to get an array of all values. Then, send those values through array.some to make sure they all exist.

const arr = Object.values(req.query);
const hasEmptyKey = arr.some(val => !val);

This assumes req.query has all the keys even if they're not filled out. If that's not the case, you can check for length:

const numExpectedKeys = 10;
const arr = Object.values(req.query);
const hasEmptyKey = arr.length == numExpectedKeys && arr.some(val => !val);

or even explicitly destructure every key you expect to be present:

const { query: { itemCode, totalQty, availQty, otherPropYouCareAbout } } = req;
const arr = [itemCode, totalQty, availQty, otherPropYouCareAbout];
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM