lodash使用值数组进行过滤器收集 [英] lodash Filter collection using array of values
问题描述
我想使用属性值数组过滤集合.给定一个ID数组,返回具有匹配ID的对象.是否有使用lodash
/underscore
的快捷方式?
I would like to filter a collection using array of property value. Given an array of IDs, return objects with matching IDs. Is there any shortcut method using lodash
/underscore
?
var collections = [{ id: 1, name: 'xyz' },
{ id: 2, name: 'ds' },
{ id: 3, name: 'rtrt' },
{ id: 4, name: 'nhf' },
{ id: 5, name: 'qwe' }];
var ids = [1,3,4];
// This works, but any better way?
var filtered = _.select(collections, function(c){
return ids.indexOf(c.id) != -1
});
推荐答案
如果您要大量使用这种模式,则可以创建如下所示的mixin,尽管这样做根本没有什么不同而不是原始代码.只是使它对开发人员更友好.
If you're going to use this sort of pattern a lot, you could create a mixin like the following, though, it isn't doing anything fundementally different than your original code. It just makes it more developer friendly.
_.mixin({
'findByValues': function(collection, property, values) {
return _.filter(collection, function(item) {
return _.contains(values, item[property]);
});
}
});
然后您可以像这样使用它.
Then you can use it like this.
var collections = [
{id: 1, name: 'xyz'},
{id: 2, name: 'ds'},
{id: 3, name: 'rtrt'},
{id: 4, name: 'nhf'},
{id: 5, name: 'qwe'}
];
var filtered = _.findByValues(collections, "id", [1,3,4]);
更新-上面的答案又旧又笨拙.请使用亚当·博杜奇(Adam Boduch)的答案,以获得更为优雅的解决方案.
Update - This above answer is old and clunky. Please use the answer from Adam Boduch for a much more elegant solution.
_(collections)
.keyBy('id') // or .indexBy() if using lodash 3.x
.at(ids)
.value();
这篇关于lodash使用值数组进行过滤器收集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!