4

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;
0

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

8 Comments

Thank you for clearing that up. This works perfectly. I was looking at it as an array when really it was an object. Can you look at this post and explain how selected is getting populated and turning into an object? docs.telerik.com/devtools/aspnet-ajax/controls/grid/how-to/…. I am assuming when selected[mailID] = true happens it adds a property called id to the object with a value of true?
@BlakeRivell It was always an object. The curly braces ({}) denote an object, and the square braces ([]) denote an array. Yes, selected[mailID] = true assigns true to selected property called mailID.
Thanks for clearing that up. I keep getting an error saying Object.values is not defined.
@BlakeRivell Well, Object.values() is an experimental function of JavaScript and it works only in the latest Chrome and Firefox. If you want it to work in all browsers, you'll probably need Babel to compile your code.
I am using the latest version of chrome and your snippet errors too. It is so strange because Object.keys works fine but I am unable to filter on value if I use Object.keys.
|
2

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.