2014-12-04 114 views
1

我想通过ID的键/值从数组中删除一个对象。我通常只是通过索引进行拼接,但是索引可能会发生很大的变化,因为多个用户将会操纵和更新对象,所以我想要更具体地描述一些东西 - 也就是id。所以我有一些逻辑来检查它是否仍然存在,如果是这样,请将其删除。但是我似乎无法得到相当正确的语法。我正在使用underscore.js,我不知道它是否更容易,但它值得一提。从数组中删除一个对象的ID(角度)

这里是我有 -

$scope.toggleSelection = function(typeId,name,index){ 

     //check if exists in array 
     check = $scope.multipleTypes.some(function(el) { 
      return el.name === name; 
     }); 

     //checked on/off actions 
     if($scope.items[index].checked == false || $scope.items[index].checked == undefined){ 
      //IS cecked 
      if(check){ 
       //already exists, do nothing 
      }else{ 
       $scope.multipleTypes.push({id:typeId, name:name, checked: true}); 
      } 
     }else{ 
      //IS not checked 
      if(check){ 
      var list = _.filter($scope.multipleTypes, function(element){ 
        return element.id != typeId; 
       } 
       $scope.multipleTypes = list; 

      }else{ 
       //is not there, do nothing 
      } 

     } 
    }; 

所以,如果确实存在,并检查了,它就会被推开。如果它存在并且未选中,我想通过它的ID将它从$ scope.multipleTypes中移除。我想我做错了,我想要做的就是从$ scope.multipleTypes中删除一个具有匹配ID的对象。将不胜感激任何帮助。谢谢阅读!

回答

3

如果你可以使用UnderScore Js,你可以这样做很容易。

下面是一个例子:

var someArray= [{Employee:'ved',id:20}, 

      {Employee:"ved",age:25}, 

      {Employee:"p",age:2}]; 

var a = _.findWhere(someArray,{id:25});//searching Element in Array 
var b= _.indexOf(someArray,a);// getting index. 
someArray.splice(b,1);// removing. 
0

我通常通过id找到对象,然后拼接出来。请注意,angularjs将其他属性添加到对象。

e.g

$scope.items = [......] 

var findItemByID = function(id, items){ 
    angular.forEach(items, function(item){ 
    if(item.id === id){ 
     return item; 
    } 
    }) 
    return null; 
} 

var removeItemByID = function(id, items){  
    var item = findItemByID(id);  
    if(item){ 
    items.splice(items.indexOf(item), 1);  
    } 
} 

//you can now do removeItemByID(id, $scope.items); 

//I have not tested this code and it may have syntax errors. hope you get the idea. 

乔希