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")); // falseBoolean(Number("1")); // true