假设我有一个名为completeArray的observableArray和另一个名为pickedArray的observableArray,第二个数组(pickedArray)包含completeArray的一些对象。从这两个数组中,我需要创建另一个observableArray,它将包含我的completeArray中所有不在pickedArray中的对象。如果有人可以帮助我如何完成,请评论是否需要澄清一些事情。谢谢!
答案 0 :(得分:1)
使用completeArray
与pickedArray
之间差异的computed observable数组。
var ViewModel = function () {
var self = this;
self.completeArray = ko.observableArray([{id: 1, name: "john"}, {id: 2, name: "bill"}, {id: 3, name: "tom"}]);
self.pickedArray = ko.observableArray([{id: 1, name: "john"}, {id: 3, name: "tom"}]);
self.diffArray = ko.computed(function() {
return ko.utils.arrayFilter(self.completeArray(), function(completeItem) {
var sameItem = false;
ko.utils.arrayForEach(self.pickedArray(), function(pickedItem) {
if(pickedItem.id == completeItem.id && pickedItem.name == completeItem.name) {
sameItem = true;
return; // break out of this loop
}
});
return !sameItem;
});
}, self);
};
$(function () {
var vm = new ViewModel();
ko.applyBindings(vm);
});
<h1>Complete Array</h1>
<div data-bind="foreach: completeArray()">
<span data-bind="text: $data.name"></span>
</div>
<h1>Picked Array</h1>
<div data-bind="foreach: pickedArray()">
<span data-bind="text: $data.name"></span>
</div>
<h1>Diff Array</h1>
<div data-bind="foreach: diffArray()">
<span data-bind="text: $data.name"></span>
</div>
完整阵列
约翰比尔汤姆
拾取阵列
约翰汤姆
Diff Array
纸币