简体   繁体   English

对象的过滤器数组通过属性[AngularJS]删除重复项

[英]Filter array of objects remove duplicates by property [AngularJS]

I have $scope.notys array in my controller and ng-repeat : 我的控制器和ng-repeat$scope.notys数组:

<li ng-repeat="x in notys" class="item js-item">
...

From my controller I push data into array like this: 从我的控制器,我将数据推入数组,如下所示:

$scope.notys.push(data);

Every data have uniques id property data.id 每个data都有唯一ID属性data.id

Question is how can I update/replace object where property is same with last data.id which comes from ajax? 问题是如何更新/替换属性与来自ajax的最后一个data.id相同的对象?

So I need to do something like this: 所以我需要做这样的事情:

  1. Get data from ajax 从ajax获取data

  2. Now have data.id from ajax I need to check if in $scope.notys exists object with same data.id 现在有来自ajax的data.id我需要检查$scope.notys存在具有相同data.id对象

  3. If exists then replace it with last data, if not then just push data 如果存在,则将其替换为最后一个数据,如果不存在,则只需push数据

You can reduce your array into key-value pairs (id-index) using array.reduce . 您可以使用array.reduce将数组简化为键-值对(id-index)。 If the id exists as a key, then you easily have the index. 如果id作为密钥存在,那么您很容易获得索引。 You can then array.splice using that index to splice off the old and put in the new. 然后,您可以使用该索引来array.splice剪接旧的并放入新的。

 var arr = [{id:1, value:'foo'},{id:2, value:'bar'}] var idIndexMap = arr.reduce(function(carry, item){ carry[item.id] = item.value; return carry; }, {}); var newItem = {id:1, value: 'baz'}; var indexOfExisting = idIndexMap[newItem.id]; if(indexOfExisting !== undefined) arr.splice(indexOfExisting, 1, newItem); document.write(JSON.stringify(arr)); 

I found this simple solution: 我找到了这个简单的解决方案:

angular.forEach($scope.notys, function (value, key) {
    if(value.id === data.id) $scope.notys.splice(key,1);
});
$scope.notys.push(data);

First I remove element if element exists with same id and then push new element. 首先,如果元素存在具有相同的ID,则删除元素,然后推送新元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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