javascript - How to filter an object array by a string with underscore.js -
this how object array looks like:
[ {"id":"1","name":"john"}, {"id":"2","name":"jose"}, {"id":"3", "name":"mike"} ]
i want filter string "jo" can bring me first , second item.
how can make return objects in same "object array" form such this:
[ {"id":"1","name":"john"}, {"id":"2","name":"jose"} ]
the object filtered on autocomplete dropdown menu created "select2.js" library.
this create using examples in stackoverflow far:
("something do" part have failed, other parts work well)
$parameterselect.select2({ data : { results : $scope.parameters, text : 'name' }, // init selected elements value initselection : function (element, callback) { var initialdata = []; $(element.val().split(",")).each(function () { initialdata.push({ id : this, text: }); }); callback(initialdata); }, formatselection : formatfunction, formatresult : formatfunction, multiple : true, formatloadmore : 'loading more...', placeholder : "select parameters", // query pagination query : function (q) { var pagesize, results; pagesize = 20; // or whatever pagesize results = []; if (q.term && q.term !== "") { // heads up; _.filter function use underscore (actually lo-dash) here results = _.filter(this.data, function (e) { //something }); } 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 function tests regexp against name property of each element.
_.filter(array, function(elt) { return /jo/i.test(elt.name); })
Comments
Post a Comment