Reputation: 24325
Is there a way to return a filtered list of new objects with knockout.js or jquery. I want to return a list of items that have IsSelected and create a new object from it, otherwise I dont want to return it.
return ko.utils.arrayForEach(result.items, function (item) {
if (item.IsSelected)
return {};
return false;
});
Upvotes: 0
Views: 3733
Reputation: 24325
Both your answers helped out. I did this below.
result.selected = ko.computed(function () {
return ko.utils.arrayMap(getSelectedItems(result.items()), function (item) {
return { Id: item.Id };
});
}, result);
function getSelectedItems(items) {
return ko.utils.arrayFilter(items, function (item) {
return item.IsSelected();
});
}
Upvotes: 4
Reputation: 7032
You can use JQuery's filter()
function:
return $(result.items).filter(function() {
return this.IsSelected;
});
See http://api.jquery.com/filter/
Better yet, you can use grep()
(See http://api.jquery.com/jQuery.grep/):
var arr = $.grep(result.items, function(item) {
return item.IsSelected;
});
return arr.length > 0 ? arr : false;
Upvotes: 4
Reputation: 1560
jQuery.grep will iterate an array and return an array based on your criteria. Then you would need to iterate this array and clone() the objects to get your desired result.
http://api.jquery.com/jQuery.grep/
var arr = [{foo:1, bar: 2}, {foo: 2 , bar: 3}, {foo: 10, bar: 2}];
var x = jQuery.grep(arr, function (item, i) {
return item.foo < 5;
});
//x = [{foo:1, bar:2}, {foo: 2, bar: 3}]
var y = [];
// here is the create a new object part
// clone your objects (you could use jQuery.clone() if they are elements).
x.each(function (item) {
y.push(jQuery.extend({}, $(this)));
});
Upvotes: 1