Blake Rivell Blake Rivell - 3 months ago 25
Javascript Question

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;

Answer

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)

Comments