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

时间:2016-03-09 16:55:12

标签: javascript arrays angularjs

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

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

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",
}

5 个答案:

答案 0 :(得分:2)

应该这么简单:

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

答案 1 :(得分:0)

使用indexOf获取拼接的位置;

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

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

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

我认为最好的想法是仅使用滤镜数组的方法。没有外部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)
});