Lodash通过匹配ids数组从数组中删除对象

问题描述 投票:7回答:2

我有一组对象,如:

var a = [
  {id: 1, name: 'A'},
  {id: 2, name: 'B'},
  {id: 3,  name: 'C'},
  {id: 4, name: 'D'}
];

和Ids数组我想从数组中删除a:

var removeItem = [1,2];

我想通过匹配array a包含的id来从removeItem array中删除对象。我怎么能用lodash实现。

我检查了lodash的_.remove方法,但这需要一个特定的条件来从数组中删除一个项目。但我有我要删除的ID列表。

javascript arrays lodash
2个回答
6
投票

如你所述,你需要_.remove方法,你提到的具体条件是removeItem数组是否包含数组的checked元素的id

var removeElements = _.remove(a, obj => removeItem.includes(obj.id));
// you only need to assign the result if you want to do something with the removed elements.
// the a variable now holds the remaining array

3
投票

你必须将predicate函数传递给.removelodash方法。

var final = _.remove(a, obj => removeItem.indexOf(obj.id) > -1);

使用indexOf方法。

indexOf()方法返回可在数组中找到给定元素的第一个索引,如果不存在则返回-1。

您可以使用native javascript使用filter方法来执行此操作,该方法接受回调函数作为参数。

var a = [
  {id: 1, name: 'A'},
  {id: 2, name: 'B'},
  {id: 3,  name: 'C'},
  {id: 4, name: 'D'}
];
var removeItem = [1,2];
a = a.filter(function(item){ 
   return removeItem.indexOf( item.id ) == -1; 
});
console.log(a);

filter方法只是通过应用回调函数创建一个新数组。

来自文档:

filter()方法创建一个新数组,其中包含所有传递由提供的函数实现的测试的元素。

如果要修改原始数组,请使用splice方法。

var a = [
  {id: 1, name: 'A'},
  {id: 2, name: 'B'},
  {id: 3,  name: 'C'},
  {id: 4, name: 'D'}
];
var removeItem = [1,2];
removeItem.forEach(function(id){
   var itemIndex = a.findIndex(i => i.id == id);
   a.splice(itemIndex,1);
});
console.log(a);
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.