如何通过 underscore.js 的字符串过滤对象数组

How to filter an object array by a string with underscore.js

这是我的对象数组的样子:

[
  {"id":"1","name":"John"},
  {"id":"2","name":"Jose"},
  {"id":"3", "name":"Mike"}
]

我想用 "jo" 这样的字符串过滤它,这样它就可以给我第一个和第二个项目。

如何使 return 对象具有相同的 "object array" 形式,例如:

[
  {"id":"1","name":"John"},
  {"id":"2","name":"Jose"}
]

在 "select2.js" 库创建的自动完成下拉菜单中过滤的对象。

到目前为止,这是我使用 Whosebug 中的示例创建的内容:

("something to do"部分是我失败的地方,其他部分都很好)

$parameterSelect.select2({
    data : {
        results : $scope.parameters,
        text : 'name'
    },
// init selected from elements value
initSelection    : function (element, callback) {
    var initialData = [];

    $(element.val().split(",")).each(function () {
        initialData.push({
            id  : this,
            text: this
        });
    });
    callback(initialData);
},
formatSelection : formatFunction,
formatResult : formatFunction,
multiple : true,
formatLoadMore   : 'Loading more...',
placeholder : "Select parameters",
// query with pagination
query            : function (q) {
    var pageSize,
    results;
    pageSize = 20; // or whatever pagesize
    results  = [];
    if (q.term && q.term !== "") {
    // HEADS UP; for the _.filter function i use underscore (actually lo-dash) here
       results = _.filter(this.data, function (e) {
            //something to do
       });
    } else if (q.term === "") {
        results = this.data;
    }
    q.callback({
        results: results.results.slice((q.page - 1) * pageSize, q.page * pageSize),
        more   : results.results.length >= q.page * pageSize
    });
}
});

使用针对每个元素的名称 属性 测试正则表达式的函数进行过滤。

_.filter(array, function(elt) { return /jo/i.test(elt.name); })

为 select2 创建您自己的匹配器:

https://select2.github.io/options.html

matcher: function (params, data) {
  // If there are no search terms, return all of the data
  if ($.trim(params.term) === '') {
    return data;
  }

  // `params.term` should be the term that is used for searching
  // `data.text` is the text that is displayed for the data object
  if (data.name.indexOf(params.term) > -1) {
    var modifiedData = $.extend({}, data, true);

    // You can return modified objects from here
    // This includes matching the `children` how you want in nested data sets
    return modifiedData;
  }

  // Return `null` if the term should not be displayed
  return null;
}