I want to write a ternary operator based on the following;
var statusJSON = {
'- Select -': '',
'Active': true,
'Inactive': false
};
Currently I have
statusFlag: $('#statusFlag').val() == 'true' ? true : false
This works fine for true
and false
values, but does not handle the 3rd condition (i.e. empty ""
)
How do I handle the same ?
statusFlag: $('#statusFlag').val() == 'true' ? true :
$('#statusFlag').val() == '' ? 'empty' : false
You can just add multiple conditions like this:
a ? b : (c ? d : e)
()
aren't necessary, but in my opinion, they improve readability when you write it without linebreaks.
This means:
if(a){
b
}else{
if(c){
d
}else{
e
}
}
So, basically, you're nesting another ternary operator in the else
clause of the previous one. You can go as far as you'd like with this:
a ? b : // if(a) then `b`
c ? d : // else, if(c) then `d`
e ? f : // else, if(e) then `f`
g ? h : // else, if(g) then `h`
i ? j : k // else, if(i) then `j`, else `k`
Try to nest the ternary
operator,
statusFlag: $('#statusFlag').val() == 'true' ?
true : $('#statusFlag').val() == 'false' ? false : "empty";
You want to use 2 conditionals in the ternary expression, something like:
value = (condition1) ? a : (condition2) ? c : d;
Your case:
statusFlag: $('#statusFlag').val() == 'true' ? true :
$('#statusFlag').val() == '' ? 'empty' : false
You can use statusJSON
as a lookup table:
var val = $('#statusFlag').val();
… statusFlag: val in statusJSON ? statusJSON[val] : false /*or whatever*/
If you're sure that only the three values do occur, or are fine with an undefined
outcome otherwise, you might as well just use
… statusFlag: statusJSON[$('#statusFlag').val()]