如何使用 javascript 或 lodash 从数组中删除项目
How can I remove an item from an array using either javascript or lodash
我的对象在下面。我在 angular 中使用它并在其中注入了 lodash。我想使用 choice2 删除第二个项目作为我要传递给匹配的项目。
$scope.choices = [{ id: 'choice1' }, { id: 'choice2' }, { id: 'choice3'
_.remove($scope.choices, function(n) {
return n.id == 'choice2';
});
在vanilla-js中,如果你不介意创建一个新对象,你可以使用filter
:
$scope.choices = $scope.choices.filter(function(obj) {
return obj.id !== 'choice2';
});
可以使用lodash的remove方法
$scope.choices = [{ id: 'choice1' }, { id: 'choice2' }, { id: 'choice3' }];
_.remove($scope.choices, function(n) {
return n.id == 'choice2';
});
_.filter($scope.choices, function(choices) {
if(choices.id !== 'choice2') {
// do something
}
});
如果您想尝试其他选择,这是执行此操作的编程方式。您不仅要直接删除一个选项,就这样保留它,在我的情况下,您正在删除该选项,并告诉应用程序在忽略它之后,然后去做一些事情。如果您只想删除该选项,请选择 xavier hans answer
_.remove
方法通过删除第二个参数中传递的任何匹配项来扩充给定的数组。
在这种情况下,传递一个具有属性 id
和变量值 id
的对象。当遍历对象数组时,lodash 将删除与 attribute/value 配对匹配的任何对象。
参见下面的示例:
$scope.choices = [{ id: 'choice1' }, { id: 'choice2' }, { id: 'choice3' }]
var id = 'choice2';
_.remove($scope.choices, {id: id});
console.log(choices)
我的对象在下面。我在 angular 中使用它并在其中注入了 lodash。我想使用 choice2 删除第二个项目作为我要传递给匹配的项目。
$scope.choices = [{ id: 'choice1' }, { id: 'choice2' }, { id: 'choice3'
_.remove($scope.choices, function(n) {
return n.id == 'choice2';
});
在vanilla-js中,如果你不介意创建一个新对象,你可以使用filter
:
$scope.choices = $scope.choices.filter(function(obj) {
return obj.id !== 'choice2';
});
可以使用lodash的remove方法
$scope.choices = [{ id: 'choice1' }, { id: 'choice2' }, { id: 'choice3' }];
_.remove($scope.choices, function(n) {
return n.id == 'choice2';
});
_.filter($scope.choices, function(choices) {
if(choices.id !== 'choice2') {
// do something
}
});
如果您想尝试其他选择,这是执行此操作的编程方式。您不仅要直接删除一个选项,就这样保留它,在我的情况下,您正在删除该选项,并告诉应用程序在忽略它之后,然后去做一些事情。如果您只想删除该选项,请选择 xavier hans answer
_.remove
方法通过删除第二个参数中传递的任何匹配项来扩充给定的数组。
在这种情况下,传递一个具有属性 id
和变量值 id
的对象。当遍历对象数组时,lodash 将删除与 attribute/value 配对匹配的任何对象。
参见下面的示例:
$scope.choices = [{ id: 'choice1' }, { id: 'choice2' }, { id: 'choice3' }]
var id = 'choice2';
_.remove($scope.choices, {id: id});
console.log(choices)