0

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.

4 Answers 4

2

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

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

2 Comments

@drjerry didn't ask to do it using iteration.
using iteration is the simplest way, if there is no native functionality. @drjerry didn't prescribe iteration, but also didn't proscribe it. an implied preference was given but nothing specific
1

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; 

1 Comment

This answer is not actually right. developer.mozilla.org/en/JavaScript/Reference/Global_Objects/… - here you can see all browsers list that are support this functionality. If it's okey for you - use it, but this way is not for me :)
1

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.

2 Comments

Thanks for the underscore_lib link I will investigate, however i'm a bit reluctant in including yet another javascript library. So I'll stick with the jQuery's grep.
just 3Kb of code. But functionality is great. I always use this lib for templating and workin with objects and arrays.
0

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}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.