I am trying to end up with 2 arrays of objects, a & b. If the key 'name' appears in array a, I do not want it to appear in b.
var characters = [
{ 'name': 'barney', 'blocked': 'a', 'employer': 'slate' },
{ 'name': 'fred', 'blocked': 'a', 'employer': 'slate' },
{ 'name': 'pebbles', 'blocked': 'a', 'employer': 'na' },
{ 'name': 'pebbles', 'blocked': 'b', 'employer': 'hanna' },
{ 'name': 'wilma', 'blocked': 'c', 'employer': 'barbera' },
{ 'name': 'bam bam', 'blocked': 'c', 'employer': 'barbera' }
];
var a = _.filter(characters, { 'blocked': 'a' });
var z = _.pluck(a,'name');
var b = _.difference(characters, a);
_(z).forEach(function (n) {
//_.pull(b, _.filter(b, { 'name': n }));
//b = _.without(b, { 'name': n });
// b = _.without(b, _.filter(b, { 'name': n }));
_.without(b, _.filter(b, { 'name': n }));
});
The code runs, but array "b" is never altered. What I expect is for array "b" to have the two objects with the names wilma and bam bam. I tried doing it without a loop.
var c = _.without(b, _.filter(b, { 'name': 'pebbles' }));
var d = _.without(b, { 'name': 'pebbles' });
var f = _.pull(b, { 'name': 'pebbles' });
though the code executes, pebbles will not go.
The Lodash _. unset() method is used to remove the property at the path of the object. If the property is removed then it returns True value otherwise, it returns False.
Lodash helps in working with arrays, strings, objects, numbers, etc. The _. omit() method is used to return a copy of the object that composed of the own and inherited enumerable property paths of the given object that are not omitted. It is the opposite of the _. pick() method.
The _. get() function is an inbuilt function in the Underscore. js library of JavaScript which is used to get the value at the path of object. If the resolved value is undefined, the defaultValue is returned in its place. Syntax: _.get(object, path, [defaultValue])
You can use remove()
inside the forEach()
to achieve the result you want...
_(z).forEach(function (n) {
_.remove(b, { 'name': n });
});
The code can be further simplified by removing z
and forEach()
...
var a = _.filter(characters, { 'blocked': 'a' });
var b = _(characters)
.difference(a)
.reject(function (x) {
return _.where(a, { 'name': x.name }).length;
})
.value();
JSFiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With