简体   繁体   English

lodash过滤器集合由其他集合

[英]lodash filter collection by other collection

I've already looked into this for a couple of days and feel like I'm missing an obvious implementation here. 我已经研究了几天,感觉好像在这里缺少一个明显的实现。

(see lodash Filter collection using array of values for something similar). (有关类似信息,请参见lodash使用值数组进行过滤器收集 )。

What I want to do is take a collection of items that a user already has, and then use that to filter from the entire list of items. 我要做的是收集用户已经拥有的项目集合,然后使用该集合从整个项目列表中进行过滤。 There are number of ways to iterate through the list and create a new collection and return it, or a way to potentially create a mixin that does this, but I was curious if there's just a chain of one-liners or a concept I'm missing. 有很多方法可以遍历列表并创建一个新集合并返回它,或者有可能创建一个可以做到这一点的mixin,但是我很好奇是否只有一排线或一个概念失踪。 The goal is to do a deep comparison of each object in the collection to determine equivalence. 目的是对集合中的每个对象进行深层比较以确定等效性。

Here's the example (jsFiddle here: http://jsfiddle.net/kxLt534f/ ) 这是示例(此处的jsFiddle: http : //jsfiddle.net/kxLt534f/

var collection = [
    {id:1, name:'one'},
    {id:2, name:'two'},
    {id:3, name:'three'}
];

var filter = [
    {id:2, name:'two'}
];

// what I want to be able to do
// var result = _.someFilterMethod(collection,filter);

// what it looks liked I'll have to do
var filtered = _.select(collection, function(c){
  var same = false;
  _.forEach(filter,function(f) {
     same = _.isEqual(f,c);
  });
  return !same;
});

console.warn(filtered); // output is : [{id:1,name:'one',id:3,name:'three'}]

There's gotta be a nicer way to do this, but I for the life of me can't see it. 有一种更好的方法可以做到这一点,但是我一生都看不到它。 Any suggestions would be appreciated! 任何建议,将不胜感激!

The function _.intersectionWith was added in lodash 4.0, it should do exactly what you want. 该功能_.intersectionWith在lodash 4.0加入,它应该做的正是你想要的。 Use it as follows: 如下使用它:

var collection = [
    {id:1, name:'one'},
    {id:2, name:'two'},
    {id:3, name:'three'}
];

var filter = [
    {id:2, name:'two'}
];


// _.isEqual performs a deep comparison
_.intersectionWith(collection, filter, _.isEqual) // [{"id":2,"name":"two"}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM