Skip to content

Instantly share code, notes, and snippets.

@sourcec0de
Created April 1, 2014 13:32
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save sourcec0de/9914035 to your computer and use it in GitHub Desktop.
Save sourcec0de/9914035 to your computer and use it in GitHub Desktop.
Select keys from a javascript object using a regular expression. Returns an object containing only the keys that matched the expression in the original object.
var keyMatch = function(o,r){
var c = 0;
var nO = {};
Object.keys(o).forEach(function(k){
c++;
no[k] = k.match(r) ? o[k] : void 0;
});
return ( ~c ? JSON.stringify(JSON.parse(nO)) : null );
};
var test = {
abc: 'foo',
acb: 'foo',
bac: 'bar'
};
keyMatch(test,/^a/);
// Returns
// ===============
// {
// abc: 'foo',
// acb: 'foo'
// }
@ecesar88
Copy link

It did not work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment