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

javascript - Using jQuery grep on an object - Stack Overflow

programmeradmin1浏览0评论

I have an object which looks like that:

const myObject = {
  3723723: null
 ,3434355: true
 ,9202002: null
}

Using jQuery grep method I need to get the count of the array where the value is not null.

const result = $.grep(myArray, function (k, v) { return v != null; });
const count = result.length;

I have an object which looks like that:

const myObject = {
  3723723: null
 ,3434355: true
 ,9202002: null
}

Using jQuery grep method I need to get the count of the array where the value is not null.

const result = $.grep(myArray, function (k, v) { return v != null; });
const count = result.length;
Share Improve this question edited Aug 17, 2016 at 18:06 Michał Perłakowski 92.9k30 gold badges163 silver badges188 bronze badges asked Aug 17, 2016 at 17:54 Blake RivellBlake Rivell 13.9k33 gold badges130 silver badges261 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 4

The variable you're talking about is actually not an array, but an object.

You don't need jQuery to find the number of values which are not null. Call the Object.values() function to get the values of that object as an array, then use the filter() method to filter out values which are null and then check the length property.

const myObject = {
  3723723: null
 ,3434355: true
 ,9202002: null
}

console.log(Object.values(myObject).filter(x => x !== null).length)

Alternative solution using Object.keys():

const myObject = {
  3723723: null
 ,3434355: true
 ,9202002: null
}

console.log(Object.keys(myObject)
  .map(x => myObject[x])
  .filter(x => x !== null).length)

In JavaScript you can use objects to get data structure you want.

var data = {
  3723723: null,
  3434355: true,
  9202002: null
}

And to count properties where the value isn't null you can use Object.keys() to get array of object keys and then reduce() to get count.

var data = {
  3723723: null,
  3434355: true,
  9202002: null
}

var result = Object.keys(data).reduce(function(r, e) {
  if(data[e] != null) r += 1;
  return r;
}, 0);

console.log(result)

发布评论

评论列表(0)

  1. 暂无评论