2014-03-04 58 views
0

我的模型是從骨幹模式陣列屬性刪除元素

var Storage = Backbone.Model.extend({ 
    defaults: { 
     q_category_id : 2, 
     dimension: [] 
    } 
}); 

我充滿名爲storageInfo模型實例與

{ 
    "q_category_id":2, 
    "dimension":[ 
     {"q_id":1,"q_text":"...","data_type":"1","meta":"15","answer":"152"}, 
     {"q_id":2,"q_text":"...","data_type":"1","meta":"30","answer":"302"}, 
     {"q_id":3,"q_text":"...","data_type":"1","meta":"60","answer":"602"} 
    ] 
} 

,但發送到服務器之前,我希望模型是像這樣:

{ 
    "q_category_id":2, 
    "dimension":[ 
     {"q_id":1,"answer":"152"}, 
     {"q_id":2,"answer":"302"}, 
     {"q_id":3,"answer":"602"} 
    ] 
} 

如何刪除屬性如q_text,datatypemeta從我的模型的dimension數組?

+1

小心在'defaults'可變對象,引用複製到根據需要,而不是克隆所以新車型您的「維度」數組會受到驚人的參考共享。在這種情況下,'defaults:function(){return {...}}是更好的方法。 –

回答

1

您可以使用下劃線mappick方法來做到這一點相當簡潔:

storageInfo.dimensions = _.map(storageInfo.dimensions, function(obj) { 
    return _.pick(obj, 'p_id', 'answer'); 
}); 
1

您可以保存模型,採用順位被net.uk.sweet的建議之前,通過迭代的尺寸。 否則,試圖改變這種模式的toJSON方法,所以它總是返回字段,你寧願:

var Storage = Backbone.Model.extend({ 
    defaults: { 
    q_category_id : 2, 
    dimension: [] 
    }, 
    toJSON: function() { 
    var dims = _.pick(this.get('dimensions'), ['q_id', 'answer']); 
    return {q_category_id: this.get('q_category_id'), dimensions: dims} 
    } 
});