笨蛋 - http://plnkr.co/edit/jXdwOQR2YLnIWv8j02Yp
我正在使用 angular 来构建一个 View ,该 View 在主容器(array-A)中有一个用户列表,以及一个托管任何“选定”用户(array-B)的用户侧边栏。
第一个 (A) 包含所有用户。
[{ $$hashKey: "00F", id: "118207f5e52c3eb619a8760bc08c8224", 用户名: "John Smith"}, { $$hashKey: "00G", id: "9c2d6f31c88e7a654e64bd0d3371360a", 用户名: "Fredy Rincon"}, { ... }]
第二个 (B) 包含已选择的用户 (Firebase db) 并通过它预先填充侧边栏。如果已经选择了用户,那么他们会出现在此处,就像在数组 A 中一样。
我的目标是能够通过单击主容器中数组 A 中的项目,从数组 B/边栏 View 中添加和删除对象。
下面是我所能得到的最接近的,但它没有考虑到侧边栏上预先填充的现有用户,只是添加和删除已经存在的项目,就好像他们不在那里。
供您引用:
$scope.selectedUsers = array-B
用户 = 数组 A 中的对象
$scope.selectUser = function (user) {
console.log($scope.selectedUsers.indexOf(user))
if ($scope.selectedUsers.indexOf(user) === -1 ) {
$scope.selectedUsers.push(user);
console.log($scope.selectedUsers);
} else {
$scope.selectedUsers.splice($scope.selectedUsers.indexOf(user), 1);
console.log($scope.selectedUsers);
}
};
我真的不知道如何解决这个问题,非常感谢任何可能的帮助。
谢谢。
最佳答案
使用Array.prototype.reduce
在添加之前检查用户:
$scope.add = function(user){
var match = $scope.selectedUsers.reduce(function(prev, curr) {
return (user.id === curr.id) || prev;
}, false);
console.log(match ? 'match' : 'no match');
if (!match) $scope.selectedUsers.push(user);
};
...您的 View 看起来像:
<p ng-repeat="user in users">{{user.username}} <a ng-click="add(user)">+</a></p>
要从 selectedUsers
数组中删除用户,请使用 Array.prototype.splice
:
$scope.remove = function(index){
$scope.selectedUsers.splice(index, 1)
}
...您的 View 看起来像:
<p ng-repeat="selectedUser in selectedUsers">{{selectedUser.username}}
<a ng-click="remove($index)">--</a></p>
关于javascript - 检查数组中的对象值是否已经存在于不同的对象数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23663002/