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

15

我希望最终得到2个对象数组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 }));
});

代码可以运行,但数组 "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' });

虽然代码可以执行,但是小石头不会动。

1个回答

21

你可以在forEach()内部使用remove()来实现你想要的结果...

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

通过移除zforEach(),可以进一步简化代码...

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

JSFiddle


3
我显然太蠢了,不知道如何接受答案。我想接受它。它确实解决了我的问题。 - shiped

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接