簡體   English   中英

如何使用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”之類的字符串過濾它,以便它可以帶給我第一項和第二項。

如何使其以相同的“對象數組”形式返回對象,如下所示:

[
  {"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
    });
}
});

使用針對每個元素的name屬性測試正則表達式的函數進行過濾。

_.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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM