【问题标题】:Backbone collection filter with where and get array of objects带有位置和获取对象数组的骨干收集过滤器
【发布时间】:2013-11-26 09:34:04
【问题描述】:

我有一个这样的 json:

Constants
Contents(Array)
->Sections(Array)
-->sections.attribute1
->constants.attribute1
->constants.attribute2
Templates

我已经过滤了 json 以使用以下代码获取内容集合:

var viasModel = Backbone.Model.extend({});

var viasCollection = Backbone.Collection.extend({

    model: viasModel,

    url: TEMPLATES_SERVICE,

    parse: function(data){
        return data.contents.data;
    },
    initialize: function(){
        this.fetch();
    },
    route: function(via){
        return this.where({viaId: via});
    }
});

假设我已经使用集合 where 的路由函数进行过滤。

如何过滤 Sections(Array) 并仅获取过滤集合的部分的元素?

是不是每个路由的返回值都有一个?

this.where({viaId: via});

我必须找到如何嵌套集合吗?任何帮助将不胜感激。

--编辑--

当我将变量分配给 arr 时,我得到一个带有属性的对象。

attributes: Object

-name: 'test',
-sections: Array[9]
--0: Object
---itemId: 'inicio'
---content: Array[2]

--1: Object
---itemId: 'hola'
---content: Array[2]

我想获取sections数组的itemId === 'inicio'的内容对象。

我不想看起来很糟糕,所以如果你能指导我或给我一些帮助,我很好。

谢谢。

【问题讨论】:

  • 为了确保我理解正确:您的模型属性是一个数组,您想根据该数组中的值过滤整个集合?所以不是通过模型属性而是通过“模型属性属性”过滤它?
  • 我已经从一个属性生成了一个集合。所以现在当我制作 collectionGenerated.where(name: 'attribute');现在我想根据过滤集合中的 sectionArray 属性进行过滤。类似于:collectionGenerated.where(name: 'attribute').sections.where(itemId: 'attribute');

标签: javascript backbone.js backbone-model backbone.js-collections


【解决方案1】:

好的,感谢您的评论,看来这基本上是关于过滤数组,这是我的建议:

var arr = collectionGenerated.where(name: 'attribute');

var result = $.grep(arr, function(val) {
   return val.itemId == 'attribute';
});

结果是只包含适合两个过滤器的数组。

-- 编辑--

我猜在你的数据结构中是

var result = $.grep(arr.sections, function(val) {
 return val.itemId === 'inicio';
});

【讨论】:

  • 你是对的,过滤数组就是答案。我对您的代码所做的唯一修改是: var result = $.grep(arr[0].attributes.sections, function(val) { return val.itemId === 'inicio'; });谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-01
相关资源
最近更新 更多