admin管理员组文章数量:1416631
In Javascript, I am processing some JSON data that takes the form:
o = {
a: null,
b: null,
c: 1,
d: null
// ... 10 or so other properties that are either null or numerical
}
I'm trying to write a quick function that will process the whole object to determine if there are any non-null values for any of the keys. Any suggestions to do this efficiently and with just a few lines of code? My project already uses underscore.js, so if that can speed things up or make it briefer, all the better.
In Javascript, I am processing some JSON data that takes the form:
o = {
a: null,
b: null,
c: 1,
d: null
// ... 10 or so other properties that are either null or numerical
}
I'm trying to write a quick function that will process the whole object to determine if there are any non-null values for any of the keys. Any suggestions to do this efficiently and with just a few lines of code? My project already uses underscore.js, so if that can speed things up or make it briefer, all the better.
Share Improve this question edited Jun 21, 2012 at 6:51 Yi Jiang 50.2k16 gold badges139 silver badges136 bronze badges asked Jun 21, 2012 at 5:36 B RobsterB Robster 42.1k24 gold badges92 silver badges124 bronze badges3 Answers
Reset to default 5What about the one-liner,
_.any(_.values(a), function (v) { return !_.isNull(v) });
which will return true if there is at least one non-null value.
var hasVal = false;
for (var prop in obj) {
hasVal = obj.hasOwnProperty(prop) && obj[prop] !== null;
if (hasVal) break;
}
You could use _.find
in bination with _.isNull
:
var has_a_null = _.chain(o).find(_.isNull).isNull().value();
or similarly:
var has_a_null = _(o).find(_.isNull) === null
Demo: http://jsfiddle/ambiguous/t678w/
本文标签: javascriptHow to determine if any values in an object are nonnullStack Overflow
版权声明:本文标题:javascript - How to determine if any values in an object are non-null? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745256225a2650118.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论