Warm tip: This article is reproduced from stackoverflow.com, please click
if-statement javascript

How to check same string value for multiple properties and shorthand if statement?

发布于 2020-03-27 10:18:50

Basically if any of the value in mailPrice contain N/A or 'n/a` trying to return true its not happening looks like i am missing something , Also if there is any better approach instead of writing big if condition i would appreciate ?

main.js

const drug = {
  "isBrand": false,
  "drugName": "Hydr",
  "drugStrength": "5mg-300mg",
  "drugForm": "Tablet",
  "mailPrice": {
    "costEmployer": "0.0",
    "costToday": "N/A",
    "deductible": "n/a",
    "memberCopayAmount": "0.00",
    "penalties": "N/A",
    "totalDrugCost": "0.00"
  }
}

const priceFilterHandler = (item) => {
  let bRet = false;
  if (item.mailPrice.costEmployer === "N/A" || item.mailPrice.costEmployer === "n/a" || item.mailPrice.costToday == "N/A" || item.mailPrice.costToday === "n/a" || item.mailPrice.penalties === "N/A" || item.mailPrice.penalties === "n/a" || item.mailPrice.deductible === "N/A" || item.mailPrice.deductible === "n/a") {
    bRet = true;
  }

  return bRet;
};

console.log(priceFilterHandler(drug));
Questioner
hussain
Viewed
53
Davide Lorenzo MARINO 2019-07-03 21:53

You can define an array of possible values and rewrite it as follow:

const na = ["N/A", "n/a"];

if (na.indexOf(item.mailPrice.costEmployer) != -1 
    || na.indexOf(item.mailPrice.costToday) != -1
    || na.indexOf(item.mailPrice.penalties) != -1
     || na.indexOf(item.mailPrice.deductible) != -1) {
  ...
}

This can be useful if you have different conditions that can be applied for na, for example

 const na = ["N/A", "n/a", "na", "NA", "n.a."];