如何使用 underscore.js 基于另一个集合过滤集合

How to filter collection based on another collection using underscore.js

我有一个名为 `mainItems`` 的集合

this.mainItems;

其中包含 18 个模型。还有一个包含所选项目的集合对象:

this.seletedItems;

我需要根据其他集合过滤主集合对象。

我试过以下方法:

    var that = this;
    var model = _.reject(that.filteredItems.models, function(model1){
        return _.filter(that.collection.models, function(model2) {
           return model1.id == model2.id;
        });
    });

但是这种方法不能正常工作。是否可以通过避免第二次迭代来过滤主要项目?

请帮忙!

您可以使用difference获取所有未选中的模型。

var mainItems = [{ a: 1 }, { b: 2 }, { c: 3 }];
var selectedItems = mainItems.slice(1);

console.log(_.difference(mainItems, selectedItems));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

您可以使用 Backbone 代理的 Underscore 方法来简化您的过滤器。

例如,要列出 mainItems 中的模型而不列出 selectedItems 中的模型,您可以使用

// reject the models found in selectedItems
var filtered = mainItems.reject(function(m) {
    return selectedItems.get(m.id);
});

请注意@GruffBunny 在评论中指出Collection.get is a hash lookup, making this a Backbone equivalent to the answer

还有一个演示

var mainItems = new Backbone.Collection([
    {id: 1},
    {id: 2},
    {id: 3},
    {id: 4}
]);

var selectedItems = new Backbone.Collection([
    {id: 2}
]);

var keep = mainItems.reject(function(m) {
    return selectedItems.get(m.id);
});

console.log(_.pluck(keep, 'id'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>