I have a model that is set with a JSON response from a mysql database. The model data is set with true or false into a boolean/tinyint field in the database, which uses 1
or 0
.
In my view, I have a binding that checks for a boolean with underscore's _.isBoolean
. Of course, when my model receives the data, it is set with 1
or 0
instead of true or false and the _.isBoolean
check fails.
Is there anyway to either correctly have my JSON response from mysql be a boolean true or false value instead of 1
or 0
, or preferably, is there a way to have my model update itself upon fetch (and before the view renders) to cast true
or false
based on it's 1 or 0 property?
e.g. my model's data looks like {"isChecked":"1"}
when I need it to be {"isChecked":true}
Thank you greatly for any suggestions you may have!
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))
});
}