I'm struggling with filtering a nested array using Knockout.
My goal is to filter the array by both 'tag-names' and 'name'.
For example, searching for 'whal' should display all objects that contain a tag with that name in the grid.
Here is the Fiddle link: https://jsfiddle.net/king_s/fj9L3wjz/3/
<input data-bind="value: searchQuery, valueUpdate: 'afterkeydown'" />
<div data-bind="foreach: filter" class="grid">
<p data-bind="text: name"></p>
</div>
(function(){
var ViewModel = function() {
var self = this;
var obj = { "id": 11,
"name": "mouse",
"tags": [{ "id": 1,
"name": "critter"
}]
};
var obj2 = { "id": 12,
"name": "dolphin",
"tags": [{ "id": 2,
"name": "fish"
},
{"id": 3,
"name": "whale"
}]
};
self.searchQuery = ko.observable("");
self.array = ko.observableArray([obj, obj2]);
self.filter = ko.computed(function() {
if(!self.searchQuery()) {
return self.array();
} else {
return ko.utils.arrayFilter(self.array(), function(obj) {
return obj.name.toLowerCase().indexOf(self.searchQuery().toLowerCase()) > -1;
});
}
});
};
ko.applyBindings(new ViewModel());
})();