简体   繁体   中英

Check if object value inside array, already exists in a different array of objects?

Plunker - http://plnkr.co/edit/jXdwOQR2YLnIWv8j02Yp

I'm using angular to build a view which has a list of users in the main container (array-A) and a sidebar of users which host any 'selected' users (array-B).

The first one (A) has all the users.

[{ $$hashKey: "00F", id: "118207f5e52c3eb619a8760bc08c8224", username: "John Smith" }, { $$hashKey: "00G", id: "9c2d6f31c88e7a654e64bd0d3371360a", username: "Fredy Rincon" }, { ... }]

The second one (B) has the users that are already selected (Firebase db) and through which the sidebar is pre-populated. If the users are already selected then they appear here exactly as they do in array-A.

My goal is to be able to add and remove objects from array-B / Sidebar view, by clicking on items from array-A in the main container.

The below is as close as I've been able to get but it doesn't take into account the existing users which are pre-populated onto the sidebar, and just adds and removes items that are already present, as if they weren't there.

For your reference:

$scope.selectedUsers = array-B

user = object in array-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);
  }
};

I really have no idea as to how to approach a solution for this, would really appreciate any help possible.

Thanks.

Use Array.prototype.reduce to check users before adding:

$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);
};

... where your view looks like:

<p ng-repeat="user in users">{{user.username}} <a ng-click="add(user)">+</a></p>

To remove users from the selectedUsers array, use Array.prototype.splice :

$scope.remove = function(index){
  $scope.selectedUsers.splice(index, 1)
}

...where your view looks like:

<p ng-repeat="selectedUser in selectedUsers">{{selectedUser.username}}
<a ng-click="remove($index)">--</a></p>

Working Plunker

由于似乎每个对象都有唯一的字符串ID,因此可行的方法是仅将ID存储在array-A和array-B中,将完整数据对象的字典存储在共享服务中,并使用角度过滤器在需要演示等时按ID查找完整的数据对象。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM