简体   繁体   English

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

[英]Lodash Remove objects from array by matching ids array

I have an array of objects like: 我有一组对象,如:

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

And Ids array which i want to remove from array a : 和Ids数组我想从数组中删除a:

var removeItem = [1,2];

I want to remove objects from array a by matching its ids, which removeItem array contains. 我想通过匹配其removeItem array包含的id来从array a删除对象。 How can i implement with lodash. 我怎么能用lodash实现。

I Checked lodash's _.remove method, but this need a specific condition to remove an item from array. 我检查了lodash的_.remove方法,但这需要一个特定的条件来从数组中删除一个项目。 But i have list of ids which i want to remove. 但我有我要删除的ID列表。

As you mentioned you need the _.remove method and the specific condition you mention is whether the removeItem array contains the id of the checked element of the array. 如前所述,您需要_.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

You have to pass a predicate function to .remove method from lodash . 您必须将predicate函数传递给lodash .remove方法。

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

using indexOf method. 使用indexOf方法。

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present. indexOf()方法返回可在数组中找到给定元素的第一个索引,如果不存在则返回-1。

You can do it using native javascript using filter method which accepts as parameter a callback function. 您可以使用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); 

But filter method just creates a new array by applying a callback function. 但是filter方法只是通过应用回调函数来创建一个新数组。

From documentation : 来自文档

The filter() method creates a new array with all elements that pass the test implemented by the provided function. filter()方法创建一个新数组,其中包含所有传递由提供的函数实现的测试的元素。

If you want to modify the original array use splice method. 如果要修改原始数组,请使用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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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