我试图以2个对象数组a和b结尾。
如果键“名称”出现在数组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' });
尽管代码会执行,但卵石不会消失。
最佳答案
您可以在remove()
中使用forEach()
以获得所需的结果...
_(z).forEach(function (n) {
_.remove(b, { 'name': n });
});
可以通过删除
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
关于arrays - 使用Lodash从对象/值中删除键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23919471/