我有一组对象,如:
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列表。
如你所述,你需要_.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
你必须将predicate
函数传递给.remove
的lodash
方法。
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);