ajmajmajma
ajmajmajma

Reputation: 14216

Remove an object from an from an array by it's id (angular)

I'm trying to remove an object from an array by it's key/value of ID. I would normally just splice by index, however the index might be changing quite a bit because multiple users will be manipulating and updating the object so I want to hook onto something more concrete - aka the id. So I have a bit of logic to check if it still exists and if so remove it by it's ID. However I can't seem to get the syntax quite correct. I Am using underscore.js, I don't know if it's easier with/without it but it's worth mentioning.

Here's what I have -

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

        }
    };

So if it does exist and is checked off, it gets pushed. If it does exist and is unchecked, I want to remove it from $scope.multipleTypes by it's ID. I think I Am doing this wrong, all I want to do is remove that one object that has the matching ID from $scope.multipleTypes. Would appreciate any help. Thanks for reading!

Upvotes: 1

Views: 4127

Answers (2)

Ved
Ved

Reputation: 12103

If you can use UnderScore Js, You can do it very easily.

Here is an Example:

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.

Upvotes: 3

joshua
joshua

Reputation: 4198

I normally find the object by id, then splice it out. Note that angularjs adds other properties to the object .

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.

Josh

Upvotes: 0

Related Questions