gpt4 book ai didi

backbone.js - 下划线 - 针对值数组进行过滤

转载 作者:行者123 更新时间:2023-12-02 22:31:26 26 4
gpt4 key购买 nike

我有一个集合 self.models。我还有一个对象数组,其中包含我希望应用于名为 filterArr 的集合的字段和过滤器。这方面的一个例子是:

[{field: "Account", filter: "123"}, {field: "Owner", filter: "Bob"}]

问题是,我不太确定如何遍历我的每个模型以仅返回此 filterArr 也适用的那些模型,我知道它必须类似于这个,但这是硬编码的:

self.models = _.filter(self.models, function (model) {
model = model.toJSON();
return model.Account === "123" && model.Owner === "Bob";

});

最佳答案

首先,underscore 的过滤器返回一个Array,所以您在这里有效地做的是用过滤后的数组替换您的集合。这样的事情会更合适:

this.filtered = _.filter(this.models, ...);

Backbone Collection 实现了大部分 underscore's useful functions .所以上面的解决方案远非最佳(事实上它根本不能按照你想要的方式工作),而是做这样的事情:

this.filtered = this.models.filter(function() {...});

到目前为止,通过名称获取和设置模型字段的最佳方式是getset functions Backbone Model,那么为什么不使用它们呢? Model.toJSON() 有效,但您只是在复制 attributes - 不必要的散列。

this.filterObj = { // Why not make it an object instead of array of objects
"Account": "123",
"Owner": "Bob"
};
this.filtered = this.models.filter(function(model) {
// use the for in construct to loop the object
for (filter in filterObj) {
// if the model doesn't pass a filter check, then return false
if (model.get(filter) !== filterObj[filter]) return false;
}
// the model passed all checks, return true
return true;
});

希望这对您有所帮助!

关于backbone.js - 下划线 - 针对值数组进行过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12192621/

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