简体   繁体   中英

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 . 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:

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.

You can use native js method to do that.

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

if you are using ES6 its even more simple

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:

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.

With plain JS this would work:

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()

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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