简体   繁体   English

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

[英]How to remove an object from an array based on another array with Lodash?

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 .由于456存在于arr ,我想从obj删除该对象。 Hence being the final result of:因此是最终结果:

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

I have tried both omit and pullByAll yet had no luck:我已经尝试了omitpullByAll但没有运气:

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

What would be the best approach to this while using Lodash ?使用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.我知道为此创建一个 Javascript 函数会非常简单,尽管我的应用程序需要经常执行此操作,因此拥有一个可访问的简单 Lodash 函数会很好。

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.这个视频很好地解释了这个概念。

As asked, here it is in lodash:正如所问,这是在 lodash 中:

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

We can debate plain js vs lodash till the cows come home, but 1) the question asks for lodash, and 2) if objs or arr are null, the plain js answers will throw an error.我们可以争论纯 js 与 lodash 直到奶牛回家,但 1) 问题要求使用 lodash,2) 如果 objs 或 arr 为空,纯 js 答案将抛出错误。

With plain JS this would work:使用普通的 JS 这将起作用:

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

I was able to solve this with a combination of both forEach() and remove()我能够通过结合forEach()remove()来解决这个问题

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

您可以通过使用过滤器包含数组的方法来实现这一点。

const array = (objs).filter((obj) => !arr.includes(obj.user))

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

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