使用 lodash 过滤一个数组的元素与另一个数组的元素

Using lodash to filter the elements of an array with another

本文关键字:数组 元素 另一个 一个 过滤 lodash 使用      更新时间:2023-09-26

假设我有以下两个数组

[{
    name: "one"
 },
 {
   name: "two" //need an array containing this
 }
];
[{
    name: "one"
}];

如何使用 lodash 过滤第一个数组以仅包含第二个数组中未列出的元素?

试试这个

var second = [{name: "one"}, {name: "two"}];
var first  = [{name: "one"}];
first  = _.pluck(first, 'name'); // get all names - ['one']
second = _.filter(second, function (el) {
  return _.indexOf(first, el.name) === -1;  // search every name in first array  
});