gpt4 book ai didi

javascript - 使用 _.differenceBy 从一个对象数组中删除另一个对象数组中的项目

转载 作者:行者123 更新时间:2023-11-30 09:41:46 26 4
gpt4 key购买 nike

我有两个对象数组:

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"
}
];

我需要创建一个数组,其中包含 defendentList 中未包含在 dismissedDefendants 中的值。我怎样才能简单地做到这一点,无论是使用 lodash 还是标准的 JS 数组函数?我在看 lodash 的 _.differenceBy ,因为它有一个迭代器,但我不太清楚如何。

更新:此示例中所需的最终结果只是一个包含不匹配对象的数组:

  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() 的 ES6 解决方案和 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);

关于javascript - 使用 _.differenceBy 从一个对象数组中删除另一个对象数组中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40837662/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com