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/
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745256226a4618973.html
评论列表(0条)