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",
...
]
var filteredNames = Object.keys(names).filter((name) => /Peter/.test(name));
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/)
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 );
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With