我有一个模型,该模型设置了来自 mysql 数据库的 JSON 响应。模型数据以 true 或 false 设置到数据库中的 bool /tinyint 字段中,该字段使用 1
或 0
。
在我看来,我有一个绑定(bind)来检查带有下划线的 _.isBoolean
的 bool 值。当然,当我的模型接收到数据时,它被设置为 1
或 0
而不是 true 或 false 并且 _.isBoolean
检查失败.
有没有办法让来自 mysql 的 JSON 响应正确地成为 bool 值 true 或 false 而不是 1
或 0
,或者最好有一种方法让我的模型根据它的 1 或 0 属性在获取时(以及在 View 呈现之前)更新自身以转换 true
或 false
?
例如当我需要它时,我的模型数据看起来像 {"isChecked":"1"}
{"isChecked":true}
非常感谢您提出任何建议!
最佳答案
您只需要使用+
将string
转换为int
,然后使用!!
将结果转换为boolean :
var response = {"isChecked":"1"};
response.isChecked = !!+response.isChecked
您可以在 parse
方法中执行此操作:
parse: function (response) {
response.isChecked = !!+response.isChecked;
return response;
}
更新:7 年后,我发现 Number(string)
转换更优雅。改变一个对象也不是最好的主意。话虽这么说:
parse: function (response) {
return Object.assign({}, response, {
isChecked: !!Number(response.isChecked), // OR
isChecked: Boolean(Number(response.isChecked))
});
}
关于javascript - 如何在模型获取时将 1 转换为 true 或将 0 转换为 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16313222/