javascript - How to determine if any values in an object are non-null? - Stack Overflow

In Javascript, I am processing some JSON data that takes the form:o = {a: null,b: null,c: 1,d: null .

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 badges
Add a ment  | 

3 Answers 3

Reset to default 5

What 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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信