Multiply original formula by 1 Note: You can also divide original formula by 1 or add 0 to original formula to change the return TRUE to 1 and FALSE to 0.
You can convert True and False to strings 'True' and 'False' with str() . Non-empty strings are considered True , so if you convert False to strings with str() and then back to bool type with bool() , it will be True .
In Python True and False are equivalent to 1 and 0. Use the int() method on a boolean to get its int values. int() turns the boolean into 1 or 0. Note: that any value not equal to 'true' will result in 0 being returned.
To convert String to Boolean, use the parseBoolean() method in Java. The parseBoolean() parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".
All you need is convert string
to int
with +
and convert the result to boolean with !!
:
var response = {"isChecked":"1"};
response.isChecked = !!+response.isChecked
You can do this manipulation in the parse
method:
parse: function (response) {
response.isChecked = !!+response.isChecked;
return response;
}
UPDATE: 7 years later, I find Number(string)
conversion more elegant. Also mutating an object is not the best idea. That being said:
parse: function (response) {
return Object.assign({}, response, {
isChecked: !!Number(response.isChecked), // OR
isChecked: Boolean(Number(response.isChecked))
});
}
Use a double not:
!!1 = true;
!!0 = false;
obj.isChecked = !!parseInt(obj.isChecked);
Here's another option that's longer but may be more readable:
Boolean(Number("0")); // false
Boolean(Number("1")); // true
You could assign the comparison of the property to "1"
obj["isChecked"] = (obj["isChecked"]==="1");
This only evaluates for a String value of "1"
though. Other variables evaulate to false like an actual typeof number
would be false. (i.e. obj["isChecked"]=1
)
If you wanted to be indiscrimate about "1"
or 1
, you could use:
obj["isChecked"] = (obj["isChecked"]=="1");
console.log(obj["isChecked"]==="1"); // true
console.log(obj["isChecked"]===1); // false
console.log(obj["isChecked"]==1); // true
console.log(obj["isChecked"]==="0"); // false
console.log(obj["isChecked"]==="Elephant"); // false
Same concept in PHP
$obj["isChecked"] = ($obj["isChecked"] == "1");
The same operator limitations as stated above for JavaScript apply.
The 'double not' also works. It's confusing when people first read it but it works in both languages for integer/number type values. It however does not work in JavaScript for string type values as they always evaluate to true:
!!"1"; //true
!!"0"; //true
!!1; //true
!!0; //false
!!parseInt("0",10); // false
echo !!"1"; //true
echo !!"0"; //false
echo !!1; //true
echo !!0; //false
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