使用_.differenceBy从另一个对象数组中删除一个对象数组中的项 [英] Remove items from one array of objects from another array of objects with _.differenceBy
本文介绍了使用_.differenceBy从另一个对象数组中删除一个对象数组中的项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个对象数组:
var defendantList = [
{
label: "Joe BLow"
value: "Joe Blow"
},
{
label: "Sam Snead"
value: "Sam Snead"
},
{
label: "John Smith"
value: "John Smith"
},
];
var dismissedDefendants = [
{
date: 'someDateString',
value: "Joe Blow"
},
{
date: "someOtherDateString",
value: "Sam Snead"
}
];
我需要创建一个数组,其中包含被告列表中未包含的来自被告列表的值.如何使用lodash或标准JS数组函数简单地做到这一点?我正在查看lodash的 _.differenceBy ,因为它具有迭代器,但是我还不太清楚怎么做.
I need to create an array that has values from defendantList that are not contained in dismissedDefendants. How can I do that simply, either with lodash or a standard JS array function? I'm looking at lodash's _.differenceBy, since it has an iteratee, but I can't quite figure out how.
更新:此示例中所需的最终结果只是对象不匹配的数组:
UPDATE: the desired end result in this example is just an array with the non-matching object:
var newArray = [
{
label: "John Smith"
value: "John Smith"
},
];
谢谢.
推荐答案
使用 _.differenceBy()
:
_.differenceBy(defendantList, dismissedDefendants, 'value');
var defendantList = [
{
label: "Joe BLow",
value: "Joe Blow"
},
{
label: "Sam Snead",
value: "Sam Snead"
},
{
label: "John Smith",
value: "John Smith"
},
];
var dismissedDefendants = [
{
date: 'someDateString',
value: "Joe Blow"
},
{
date: "someOtherDateString",
value: "Sam Snead"
}
];
var result = _.differenceBy(defendantList, dismissedDefendants, 'value');
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>
以及基于 Array.prototype.filter()
和 设置
:
And an ES6 solution based on Array.prototype.filter()
and Set
:
defendantList.filter(function({ value }) {
return !this.has(value); // keep if value is not in the Set
}, new Set(dismissedDefendants.map(({ value }) => value))); //create a Set of unique values in dismissedDefendants and assign it to this
var defendantList = [
{
label: "Joe BLow",
value: "Joe Blow"
},
{
label: "Sam Snead",
value: "Sam Snead"
},
{
label: "John Smith",
value: "John Smith"
},
];
var dismissedDefendants = [
{
date: 'someDateString',
value: "Joe Blow"
},
{
date: "someOtherDateString",
value: "Sam Snead"
}
];
var result = defendantList.filter(function({ value }) {
return !this.has(value);
}, new Set(dismissedDefendants.map(({ value }) => value)));
console.log(result);
这篇关于使用_.differenceBy从另一个对象数组中删除一个对象数组中的项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文