如何在两个observablearrays之间获得减去的值(或差异)。
例如。
AllUsers = [{UserKey01,User_ABC},{UserKey02,User_DEF},{UserKey03,User_GHI},{UserKey04,User_JKL}]
SpecialUsers = [{UserKey01,User_ABC},{UserKey02,User_DEF}]
我需要
NonSpecialUsers = [{UserKey03,User_GHI},{UserKey04,User_JKL}]
下面提到的是我正在尝试的代码:
function UserViewModel(userKey,userName) {
var self = this;
self.UserKey = ko.observable(0);
self.UserName = ko.observable(0);
}
self.AllUsers = observableArray();
self.SpecialUsers = observableArray();
self.NonSpecialUsers = ko.dependentObservable(function () {
var usrs = ko.observableArray();
for (var i = 0; i < self.SpecialUsers().length; i++) {
var assignedUser = self.SpecialUsers()[i];
var x = ko.utils.arrayFilter(self.AllUsers(), function (item) {
return item.UserKey() != assignedUser.UserKey();
});
usrs.push(x);
}
return usrs;
});
有了这个,我得到一些非特殊用户*特殊用户: 即
[[{UserKey01,User_ABC},{UserKey02,User_DEF}],[{UserKey01,User_ABC},{UserKey02,User_DEF}]]
答案 0 :(得分:0)
这就是我实现它的方式:
var filteredUsrs = $.grep(self.SpecialUsers(), function (el) { return el });
var filteredUserKeys = ko.toJS(filteredUsers).map(function (elem) { return elem.UserKey; })
return $.grep(self.AllUsers(), function (u) { return filteredUserKeys.indexOf(u.UserKey()) == -1; });
不确定是否有更好的方法。