简体   繁体   中英

How can I remove an item from an array using either javascript or lodash

My object is below. I am using this in angular and have lodash injected into it. I want to remove the 2nd item using choice2 as what I would pass to match.

    $scope.choices = [{ id: 'choice1' }, { id: 'choice2' }, { id: 'choice3' 

You can use the remove method of lodash.

$scope.choices = [{ id: 'choice1' }, { id: 'choice2' }, { id: 'choice3' }];
_.remove($scope.choices, function(n) {
    return n.id == 'choice2';
});
_.remove($scope.choices, function(n) {
  return n.id == 'choice2';
});

In vanilla-js, if you don't mind creating a new object, you can use filter :

$scope.choices = $scope.choices.filter(function(obj) {
    return obj.id !== 'choice2';
});
_.filter($scope.choices, function(choices) {
   if(choices.id !== 'choice2') {
      // do something
   }
});

this is the programmatic way to do it in case that you want to play with the other choices. You are not going only straight to the point of eliminating one option and just leave it like that, in my case you are eliminating the option and you are telling to the app that after ignore it, then go and do something. If you want to just remove that choice, then go with xavier hans answer

The _.remove method augments the given array by removing any matches passed in the second argument.

In this case, pass an object with attribute id and value of your var id . When iterating over the array of objects, lodash will remove any object that matches that attribute/value pairing.

See example below:

$scope.choices = [{ id: 'choice1' }, { id: 'choice2' }, { id: 'choice3' }]
var id = 'choice2';
_.remove($scope.choices, {id: id});
console.log(choices)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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