Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do I get object keys by a pattern?

I have an object with named keys:

var names = {
  "Peter Pan": {...},
  "Peter Parker": {...},
  "Tony Stark": {...},
  ...
}

Is there a way to get all keys by a pattern eg. all keys having Peter in it?

The case is that I want to have all the filtered keys in an array eg:

var filteredNames: [
  "Peter Pan",
  "Peter Parker",
  ...
]
like image 576
ajsie Avatar asked Jul 19 '11 22:07

ajsie


3 Answers

var filteredNames = Object.keys(names).filter((name) => /Peter/.test(name));
like image 155
Gabriel Avatar answered Nov 08 '22 19:11

Gabriel


You can easily do it by looping over the keys yourself:

var filtered_keys = function(obj, filter) {
  var key, keys = [];
  for (key in obj) {
    if (obj.hasOwnProperty(key) && filter.test(key)) {
      keys.push(key);
    }
  }
  return keys;
}
// example:
var filteredNames = filtered_keys(names, /Peter/); // second parameter is a javascript regex object, so for exemple for case insensitive you would do /Peter/i    

ES6

let filtered_keys = (obj, filter) => {
  let key, keys = []
  for (key in obj)
    if (obj.hasOwnProperty(key) && filter.test(key))
      keys.push(key)
  return keys
}

// example:
let filteredNames = filtered_keys(names, /Peter/)
like image 26
Lepidosteus Avatar answered Nov 08 '22 19:11

Lepidosteus


If you want it case sensitive:

var filteredNames = [];

for( name in names ) {
    if( name.indexOf( "Peter" ) > -1 ) {
        filteredNames.push( name );
    }
}

If not:

var filteredNames = [];

for( name in names ) {
    if( /peter/gi.test( name ) ) {
        filteredNames.push( name );
    }
}
like image 3
user113716 Avatar answered Nov 08 '22 20:11

user113716