最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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/

发布评论

评论列表(0)

  1. 暂无评论