Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JS is or is not if else

How could I simplify this action below.
I realize this is ridiculous.

But everything I’m trying to do, either one works and one doesn’t and vice versa.

I need to send data if this field is not empty. if it is empty, then don’t send it: admin|power

it’s either null or not

const mreq = await Model.findOne({
  where: {
    id: req.params.id,
    old: req.params.times
  }
})
if (!mreq) {
  return
} else if (mreq.admin == null) {
  return
} else if (mreq.admin) {
  res.json(mreq.admin)
} else if (mreq.power == null) {
  return
} else if (mreq.power) {
  res.json(mreq.power)
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You don’t need all the branches that don’t return anything – just test for the two values to be .jsond in two ifs. Use optional chaining to keep things concise.

const mreq = await Model.findOne({ where: { id: req.params.id, old: req.params.times } })
if (mreq?.admin) {
    res.json(mreq.admin)
} else if (mreq?.power) {
    res.json(mreq.power)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading