简体   繁体   English

Underscore.js - 使用regexp查找对象键的值?

[英]Underscore.js - find a value of an object key using regexp?

I get an array of objects that looks like this: 我得到一个看起来像这样的对象数组:

var collection = [
  {
    name: 'hello',
    color: 'blue'
  },
  {
    name: 'world',
    color: 'brown'
  }, .... {thousands more}
];

What would be the proper way to use underscore to find out if any of the objects in the array has a value for the 'name' key equal to some regular expression? 使用下划线找出数组中的任何对象是否具有“name”键的值等于某个正则表达式的正确方法是什么?

_.contains(collection, '/goodbye/i'); <-- this won't work ->

How to tell it to use the 'name' key for searching? 如何告诉它使用'name'键进行搜索?

You could do: 你可以这样做:

filter = function (collection, key, regex) {
    return _.filter(collection, function(obj){ return obj[key].match(regex);});
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM