0

请问我怎样才能为每个产品过滤一组项目?或者如何过滤包含类别数据的项目?

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'));

感谢您的意见和回答!马克罗马特

4

2 回答 2

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 

您应该使用.groupBythen 循环对象并显示每个类别中的项目:

例子

于 2013-09-24T12:03:41.087 回答
0

使用Backbone.Collection.filter()并提供与您的类别匹配的比较器。

http://underscorejs.org/#filter

于 2013-09-24T11:52:30.720 回答