我的数据包含一个具有嵌套对象的对象,每个键都是id,我想解析集合response.payload
但是当我这样做时,集合将返回为包含嵌套对象的1个对象。任何人都可以建议我如何使每个嵌套对象成为一个模型?
JS
var data = {
"payload": {
"020": {
"sessions": ["SES1", "SES2", "SES3", "SES4"],
"account": [],
"tag": []
},
"650": {
"sessions": ["SES11", "SES12", "SES13"],
"account": ["ACCT1", "ACC2", "ACC3"],
"tag": []
},
"880": {
"sessions": ["SES900", "SES901"],
"account": ["abc", "DEF"],
"tag": ["TAG5", "TAG53"]
}
}
};
var SearchCollection = Backbone.Collection.extend({
parse: function(response) {
console.log(response.payload);
return response.payload;
}
});
var searchCollection = new SearchCollection(data, {parse: true});
console.log(searchCollection.toJSON());
我是否需要在解析中循环响应并使用密钥ID创建模型,或者创建模型并在那里进行一些解析?
JS Fiddle http://jsfiddle.net/t6w0bcu6/22/
答案 0 :(得分:2)
我会“在解析中循环响应并使用密钥ID创建模型”。这是一种方法。
var SearchCollection = Backbone.Collection.extend({
parse: function(response) {
var models = [];
_.each(response.payload,(value, key)=>{
value.id = key;
models.push(new Backbone.Model(value))
})
return models;
}
});