Is there a better way to improve the below statement to check if the val()
is 'true'
or 'false'
and if it is then it will change it to a Boolean. The reason being, some of the values may be a word.
var thisval = $(this).val();
if (thisval == "true"){
ao[id] = true;
} else if (thisval == "false"){
ao[id] = false;
} else {
ao[id] = $(this).val();
}
parseBoolean(String s) − This method accepts a String variable and returns boolean. If the given string value is "true" (irrespective of its case) this method returns true else, if it is null or, false or, any other value it returns false.
To convert a string to a boolean in TypeScript, use the strict equality operator to compare the string to the string "true" , e.g. const bool = str === 'true' . If the condition is met, the strict equality operator will return the boolean value true , otherwise false is returned.
The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string " true ".
String.prototype.bool = function() {
return (/^true$/i).test(this);
};
if ( $(this).val() == "true" || $(this).val() == "false") {
ao[id] = $(this).val().bool();
}else {
ao[id] = $(this).val();
}
Most readable:
var thisval = $(this).val();
ao[id] = thisval === 'true' ? true :
thisval === 'false' ? false :
thisval;
One-liner based on the conditional operator:
var thisval = $(this).val();
ao[id] = thisval === 'true' ? true : (thisval === 'false' ? false : thisval);
One-liner based on || and && behavior:
var thisval = $(this).val();
ao[id] = thisval === 'true' || (thisval !== 'false') && thisval || false;
Shortest one-liner (combination of the above):
var thisval = $(this).val();
ao[id] = thisval === 'true' || (thisval === 'false' ? false : thisval);
Try JSON.parse().
"true"
and "false"
are actually json representations of true
, false
. This is how ajax parses json object as a string from server side. If on server side, we return true, false => the browser will receive it as a string "true" or "false" (json representation)
if ( $(this).val() == "true" || $(this).val() == "false") {
ao[id] = JSON.parse($(this).val());
}else {
ao[id] = $(this).val();
}
DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With