[英]How to filter an object array by a string with underscore.js
This is how my object array looks like: 这是我的对象数组的样子:
[
{"id":"1","name":"John"},
{"id":"2","name":"Jose"},
{"id":"3", "name":"Mike"}
]
I want to filter it with a String like "jo" so it can bring me first and second item. 我想用“ jo”之类的字符串过滤它,以便它可以带给我第一项和第二项。
How can make it return the Objects in the same "object array" form such as this: 如何使其以相同的“对象数组”形式返回对象,如下所示:
[
{"id":"1","name":"John"},
{"id":"2","name":"Jose"}
]
The object filtered on an autocomplete dropdown menu created by "select2.js" library. 在由“ select2.js”库创建的自动完成下拉菜单中过滤的对象。
This is what I create using the examples in stackoverflow so far: 到目前为止,这是我使用stackoverflow中的示例创建的:
("something to do" part is where I have failed, other parts work well) (“要做的事情”部分是我失败的地方,其他部分工作良好)
$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); })
Create your own matcher for select2: 为select2创建自己的匹配器:
https://select2.github.io/options.html 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.