How to convert 1 to true or 0 to false upon model fetch
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
Assigning Comparison to property value
JavaScript
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");
Example Outputs
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
PHP
Same concept in PHP
$obj["isChecked"] = ($obj["isChecked"] == "1");
The same operator limitations as stated above for JavaScript apply.
Double Not
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:
JavaScript
!!"1"; //true
!!"0"; //true
!!1; //true
!!0; //false
!!parseInt("0",10); // false
PHP
echo !!"1"; //true
echo !!"0"; //false
echo !!1; //true
echo !!0; //false
Boolean(Number(myVar))
or
!!+myVar