基于键和值过滤数组

时间:2014-12-12 07:03:53

标签: javascript arrays underscore.js

我有一个以下格式的数组,我需要根据键和值进行过滤。我计划使用Underscore.js。我尝试使用以下代码,但它搜索所有字段值,但我需要根据键和值进行搜索,而不是所有键。如何使用Underscore?

请告诉我。

var sortedArray = _.sortBy(_.filter(arr, function (obj) {
                      return _.values(obj).some(function (el) {
                          return (typeof el ==="string" && el.match(new RegExp(searchStr, "i")));
                       });
                      }), function (obj){
                            return obj[colName];
                    });
}


{
  "recordsTotal": 5,
  "recordsFiltered": 5,
  "aaData": [
  {
    "firstname": "Pradeep",
    "lastname": "Kumar",
    "city": "Bangalore",
    "country": "India"
  },
  {
    "firstname": "John",
    "lastname": "Wells",
    "city": "Calcutta",
    "country": "India"
  },
  {
    "firstname": "Praveen",
    "lastname": "Garg",
    "city": "columbo",
    "country": "Srilanka"
  },
  {
    "firstname": "Joe",
    "lastname": "Wells",
    "city": "Luton",
    "country": "UK"
  },
  {
    "firstname": "Rita",
    "lastname": "Wahlin",
    "city": "houston",
    "country": "USA"
   }
 ] 
}

1 个答案:

答案 0 :(得分:0)

很抱歉,如果我无法正确发布问题。我找到了一个解决方案,并使用下面的代码。

    var searchColData=function(arr, searchStr, colName){
       var sortedArray = _.filter(arr, function (obj) {
                       return (_.property(colName)(obj).toString().match(new RegExp(searchStr, "i")));
                      });

    return sortedArray;

}

希望这有助于某人。