简体   繁体   中英

Using jQuery grep on an object

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;

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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM