使用Lodash从对象/值中删除键

时间:2022-10-03 20:10:48

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.

我正试图得到两个数组的对象,a和b。如果键'name'出现在数组a中,我不希望它出现在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.

代码运行,但是数组“b”永远不会被修改。我所期望的是数组“b”有两个名为wilma和bam bam的对象。我试着不绕圈子做这件事。

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.

虽然代码执行了,但是石子不会消失。

1 个解决方案

#1


19  

You can use remove() inside the forEach() to achieve the result you want...

您可以在forEach()中使用remove()来实现您想要的结果。

_(z).forEach(function (n) {
    _.remove(b, { 'name': n });
});

The code can be further simplified by removing z and forEach()...

可以通过删除z和forEach()进一步简化代码。

var a = _.filter(characters, { 'blocked': 'a' });
var b = _(characters)
            .difference(a)
            .reject(function (x) { 
                return _.where(a, { 'name': x.name }).length; 
            })
            .value();

JSFiddle

JSFiddle

#1


19  

You can use remove() inside the forEach() to achieve the result you want...

您可以在forEach()中使用remove()来实现您想要的结果。

_(z).forEach(function (n) {
    _.remove(b, { 'name': n });
});

The code can be further simplified by removing z and forEach()...

可以通过删除z和forEach()进一步简化代码。

var a = _.filter(characters, { 'blocked': 'a' });
var b = _(characters)
            .difference(a)
            .reject(function (x) { 
                return _.where(a, { 'name': x.name }).length; 
            })
            .value();

JSFiddle

JSFiddle