Search code examples
javascriptpropertiescountkey

Counting number of object properties with a name filter


I have an object which looks like:

{a: 1, b:2, c:3, cp1:6, cp2:7 cp3:8, cp4:9}

I'm interested in the number of cpX occurrences in my Object, is there an easy way in Javascript (or jQuery) to count the number of occurrences matching a pattern. Something like:

Object.keys(myObj,/cp\d+/).length();

I know I can iterate over it myself, but I wouldn't be surprised if this functionality is already present.


Solution

  • Object.keys() doesn't support to filter array items. But you can use the jQuery's grep() function to filter your keys.

    This one works:

    var x = {a: 1, b:2, c:3, cp1:6, cp2:7, cp3:8, cp4:9};
    var cpItemsLength = $.grep(Object.keys(x), function(n) { 
        return /cp\d+/.test(n);
    }).length;