dr jerry
dr jerry

Reputation: 10026

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.

Upvotes: 0

Views: 1193

Answers (4)

perona chan
perona chan

Reputation: 191

maybe like this

var obj = {a: 1, b:2, c:3, cp1:6, cp2:7, cp3:8, cp4:9}
var res = {}
Object.keys(obj).forEach(key => 
   key.includes('cp') && (res[key] = obj[key])
)
console.log(res) // {cp1: 6, cp2: 7, cp3: 8, cp4: 9}

Upvotes: 0

Abdul Munim
Abdul Munim

Reputation: 19217

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;

Upvotes: 1

ValeriiVasin
ValeriiVasin

Reputation: 8716

There are no special functionality in pure javascript... Objects and arrays are so poor...

You can use underscore lib for this purposes.

Code will be follow:

$(function(){
  var a = {a: 1, b:2, c:3, cp1:6, cp2:7, cp3:8, cp4:9};
  var result = _(a).chain().keys().select(function(key){ return key.match(/^cp/);}).value().length;
  $('#results').html(result);
});

Try it here.

Upvotes: 1

Kae Verens
Kae Verens

Reputation: 4079

this might do it

var obj={a: 1, b:2, c:3, cp1:6, cp2:7 cp3:8, cp4:9};
var num=0;
for (var key in obj) {
  if (/^cp/.test(key)) {
    ++num;
  }
}
alert(num);

you could probably do it using maps, but I'm not sure that there is native functionality for that

Upvotes: 2

Related Questions