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.
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.
- Why do you feel the need for using lodash? If performance is your concern, using vanilla js probably more transparent and easier to optimize. – lipp Commented May 30, 2016 at 7:08
- How many elements (magnitude) are you expecting in arr and objs respectively? Do you "re-query" objs for every request or is it "global"? – lipp Commented May 30, 2016 at 7:17
4 Answers
Reset to default 2You 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 e 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 bination of both forEach()
and remove()
_(obj).forEach(function(value) {
_.remove(arr, {
user: value
});
});