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

时间:2016-11-28 05:26:05

标签: javascript arrays lodash

我有两个对象数组:

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

我需要创建一个数组,其中包含来自被告列表的值,这些值不包含在dismissedDefendants中。我怎么能简单地用lodash或标准的JS数组函数做到这一点?我正在查看lodash的_.differenceBy,因为它有一个迭代,但我无法弄清楚如何。

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

  var newArray = [
      {
        label: "John Smith"
        value: "John Smith"
      },
    ];

感谢。

2 个答案:

答案 0 :(得分:3)

使用_.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()Set的ES6解决方案:

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);

答案 1 :(得分:0)

这是使用普通Javascript的简单解决方案。希望它有所帮助!

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

for(var i in defendantList){
    for(var j in dismissedDefendants){
      if(defendantList[i].value === dismissedDefendants[j].value){
        var index = defendantList.indexOf(defendantList[i]);
        if (index > -1) {
        defendantList.splice(index, 1);
        }
      }
    }
}
console.log(defendantList);