开发者

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",
  ...
]


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 );
    }
}


You could extend the JavaScript Array prototype, like so:

Array.prototype.regex_search = function(pattern) {
  var returns = [];
  for(var i = 0; i < this.length; i++) {
    if(this[i].match(pattern) {
      returns.push(i);
    }
  }
  if(returns.length) {
    return returns;
  } else {
    return false;
  }
}

Now I haven't actually tested this code but this would give all arrays you create in JavaScript a method .regex_search which takes an argument 'pattern'. This will either return false when no matches are found or an array of indices when elements match.

You could then iterate over this array and take those indices from the original array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜