问题描述
我有一个使用来自 mysql 数据库的 JSON 响应设置的模型.将模型数据设置为true 或false 到数据库中的boolean/tinyint 字段中,该字段使用1
或0
.
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
.
在我看来,我有一个绑定来检查带有下划线的 _.isBoolean
的布尔值.当然,当我的模型接收到数据时,它被设置为 1
或 0
而不是 true 或 false 并且 _.isBoolean
检查失败.
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.
无论如何,是否可以正确地让我的来自 mysql 的 JSON 响应是布尔值 true 或 false 值而不是 1
或 0
,或者最好有办法让我的模型在获取时(以及在视图呈现之前)更新自身以根据它的 1 或 0 属性强制转换 true
或 false
?
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?
例如我的模型数据看起来像 {"isChecked":"1"}
当我需要它是 {"isChecked":true}
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!
推荐答案
所有你需要的是用 +
将 string
转换为 int
并转换使用 !!
将结果转换为布尔值:
All you need is convert string
to int
with +
and convert the result to boolean with !!
:
var response = {"isChecked":"1"};
response.isChecked = !!+response.isChecked
您可以在 parse
方法中执行此操作:
You can do this manipulation in the parse
method:
parse: function (response) {
response.isChecked = !!+response.isChecked;
return response;
}
UPDATE:7 年后,我发现 Number(string)
转换更优雅.也改变一个对象不是最好的主意.话虽如此:
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))
});
}
这篇关于如何在模型获取时将 1 转换为 true 或将 0 转换为 false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!