user21177168
user21177168

Reputation: 13

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)
}

Upvotes: 0

Views: 88

Answers (2)

Santi Trayko
Santi Trayko

Reputation: 104

Considering that perhaps the property "admin" can be boolean (I don't konw) You can do something like this:

if(mreq && mreq.admin !== null) { 
res.json(mreq.admin);
return;
} 

if (mreq.power) {  res.json(mreq.power) }

I hope you find it useful.

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370979

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)
}

Upvotes: 5

Related Questions