如何使用带有underscore.js的字符串过滤对象数组

时间:2015-10-27 16:32:51

标签: javascript underscore.js jquery-select2

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

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

我想用像“jo”这样的字符串过滤它,这样它就可以带给我第一和第二项。

如何使它以相同的“对象数组”形式返回对象,如下所示:

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

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

这是我到目前为止使用stackoverflow中的示例创建的:

(“要做的事情”部分是我失败的地方,其他部分运作良好)

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

2 个答案:

答案 0 :(得分:2)

使用函数过滤,该函数根据每个元素的name属性测试正则表达式。

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

答案 1 :(得分:0)

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