请问如何为每种产品过滤一组商品?或者如何使用类别中的数据过滤项目?
var Categories = new Backbone.Collection();
Categories.add([
{ title: 'category 1', category_type: 'category 1' },
{ title: 'category 2', category_type: 'category 1' },
]);
var Items = new Backbone.Collection();
Items.add([
{ title: 'Product 1', category: 'category 1' },
{ title: 'Product 2', category: 'category 1' },
{ title: 'Product 3', category: 'category 2' }
]);
var byFiltred = Items.groupBy('category');
var filtred = new Backbone.Collection(byFiltred['category 1']);
console.log(filtred.pluck('title'));
感谢您的意见和答案!! Makromat
答案 0 :(得分:2)
这取决于你想得到什么。 .groupBy
返回分层对象,而.filter
(或仅.where
)符合条件的项目数组。
所以给出了这个数组:
var a = [
{ title: 'Product 1', category: 'category 1' },
{ title: 'Product 2', category: 'category 1' },
{ title: 'Product 3', category: 'category 2' }
]
_.groupBy( a, 'category' );
/* returns
{
"category 1" : [ { title: 'Product 1', category: 'category 1' }, { title: 'Product 2', category: 'category 1' } ],
"category 2" : [ { title: 'Product 3', category: 'category 2' } ]
}
*/
_.where( a, { 'category': 'category 1' });
/* returns
[ { title: 'Product 1', category: 'category 1' }, { title: 'Product 2', category: 'category 1' } ]
*/
显示分层视图,例如
category 1
product 1
product 2
category 2
product 1
您应该使用.groupBy
然后循环对象并显示每个类别中的项目:
<强> example
答案 1 :(得分:0)
使用Backbone.Collection.filter()
并提供与您的类别匹配的比较器。