如何使用Lodash从基于另一个数组的数组中删除对象?

时间:2022-03-12 07:49:12

I am trying to edit an array of objects that I have based on another array.

我正在尝试编辑基于另一个数组的对象数组。

For example, this is my array of objects:

例如,这是我的对象数组:

var objs = [{ 
   attending: 0, user: '123' 
}, { 
   attending: 0, user: '456' 
}, { 
   attending: 0, user: '789' 
}];

And this is my array:

这是我的阵列:

var arr = ['945', '456']

Since 456 exists within arr, I would like to remove that object from obj. Hence being the final result of:

由于456存在于arr中,我想从obj中删除该对象。因此是最终的结果:

var objs = [{ 
   attending: 0, user: '123' 
}, { 
   attending: 0, user: '789' 
}];

I have tried both omit and pullByAll yet had no luck:

我试过omit和pullByAll但没有运气:

var newObj = _.omit(obj, arr);
var newObj = _.pullAllBy(obj, arr, 'user');

What would be the best approach to this while using Lodash? I understand that creating a Javascript function for this would be quite simple, although my app requires this to be done quite often, so would be good to have a simple Lodash function that is accessible.

使用Lodash时最好的方法是什么?我知道为此创建一个Javascript函数会非常简单,虽然我的应用程序要求经常这样做,所以有一个可访问的简单Lodash函数会很好。

3 个解决方案

#1


1  

With plain JS this would work:

使用普通JS,这将工作:

var newObj = objs.filter(function(obj) {
   return arr.indexOf(obj.user) !== -1
})

#2


1  

You can use native js method to do that.

您可以使用本机js方法来执行此操作。

var newObj = objs.filter(function(obj) {
  return arr.indexOf(obj.user) != -1
});

if you are using ES6 its even more simple

如果你使用ES6它更简单

var newObj = objs.filter(obj => arr.indexOf(obj.user) != -1);

There is this video which explains this concept very nicely.

这段视频很好地解释了这个概念。

#3


0  

I was able to solve this with a combination of both forEach() and remove()

我能够通过forEach()和remove()的组合来解决这个问题。

_(obj).forEach(function(value) {
    _.remove(arr, {
        user: value
    });
});

#1


1  

With plain JS this would work:

使用普通JS,这将工作:

var newObj = objs.filter(function(obj) {
   return arr.indexOf(obj.user) !== -1
})

#2


1  

You can use native js method to do that.

您可以使用本机js方法来执行此操作。

var newObj = objs.filter(function(obj) {
  return arr.indexOf(obj.user) != -1
});

if you are using ES6 its even more simple

如果你使用ES6它更简单

var newObj = objs.filter(obj => arr.indexOf(obj.user) != -1);

There is this video which explains this concept very nicely.

这段视频很好地解释了这个概念。

#3


0  

I was able to solve this with a combination of both forEach() and remove()

我能够通过forEach()和remove()的组合来解决这个问题。

_(obj).forEach(function(value) {
    _.remove(arr, {
        user: value
    });
});