Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove key from object/value using Lodash

Tags:

arrays

lodash

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.

like image 651
shiped Avatar asked May 28 '14 18:05

shiped


People also ask

How do I remove a key from an object using Lodash?

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.

What is omit in Lodash?

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.

What is _ get?

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


1 Answers

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

like image 141
Anthony Chu Avatar answered Sep 20 '22 00:09

Anthony Chu