繁体   English   中英

如果值匹配,如何从数组中删除元素?

[英]How to remove element from array if values matched?

如果我在对象中找到值,我想从数组中删除这些值。

完成这项任务的最佳解决方案是什么?

ctrl.js

  var selectedOwners = [];
            $scope.deleteOwner = function(dataItem){
                var workerKey;
                var fullName;
                angular.forEach(selectedOwners,function(val,index){
                  workerKey = val.workerKey;
                  fullName = val.fullName;
                })
                if(dataItem.workeyKey === workerKey || dataItem.fullName === fullName){ 
                  selectedOwners.splice(workerKey,fullName);
                }      
            }

数组和对象

Array  selectedOwners = [{"fullName":"Johnson, Rocio","workerKey":3506},{"fullName":"Johnson, John S.","workerKey":571},{"fullName":"Johnson, Camille A.","workerKey":1368}]

Object {
    "workerKey": 3506,
    "fullName": "Johnson, Rocio",
}

应该像这样简单:

var selectedOwners = [{
    "fullName": "Johnson, Rocio",
    "workerKey": 3506
}, {
    "fullName": "Johnson, John S.",
    "workerKey": 571
}, {
    "fullName": "Johnson, Camille A.",
    "workerKey": 1368
}];

var obj = {
    "workerKey": 3506,
    "fullName": "Johnson, Rocio",
};


for (var i = 0; i < selectedOwners.length; i++) {
    if (selectedOwners[i].workerKey === obj.workerKey) {
        selectedOwners.splice(i, 1);
        break;
    }
}

请记住,for循环假定workerKey在数组中是唯一的。 这就是为什么我们只需要在workerKey属性上进行比较,并且在找到匹配项后也退出for循环的原因。

如果workerKey不是唯一的,这是循环:

for (var i = 0; i < selectedOwners.length; i++) {
    if (selectedOwners[i].workerKey === obj.workerKey &&
        selectedOwners[i].fullName === obj.fullName) {
        selectedOwners.splice(i, 1);

        // we need to decrement i by one because
        // we just removed an element from the array
        i--;
    }
}

使用indexOf获取接头的位置;

由于将对象作为dataItem传递,因此可以执行以下操作:

$scope.deleteOwner = function(dataItem){
    selectedOwners.splice(indexOf(dataItem), 1);
}

您可以使用lodash _.remove非常简单

_.remove(selectedOwners , {
          "fullName": "Johnson, Rocio",
          "workerKey": 3506    //where condition
     });

您可以使用grep函数,如下所示:

$scope.deleteOwner = function(dataItem){
            selectedOwners = $.grep(selectedOwners, function(value) {
                return value.workerKey != dataItem.workerKey 
                     && value.fullName!= dataItem.fullName;
            });      
        }

我认为最好的主意是仅使用过滤器数组的方法。 没有外部JS依赖性。

var selectedOwners = [{"fullName":"Johnson, Rocio","workerKey":3506},{"fullName":"Johnson, John S.","workerKey":571},{"fullName":"Johnson, Camille A.","workerKey":1368}]
var item = {
    "workerKey": 3506,
    "fullName": "Johnson, Rocio",
}

var resultArray = selectedOwners.filter(function(i){ 
   return !(i.fullname == item.fullname && i.workerKey == item.workerKey)
});

暂无
暂无

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

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