Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save grim-reapper/740528cffef66b411e55ecc8e482d5ae to your computer and use it in GitHub Desktop.

Select an option

Save grim-reapper/740528cffef66b411e55ecc8e482d5ae 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'
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment