从Backbone模型的数组属性中删除元素

时间:2014-03-04 13:11:53

标签: jquery backbone.js underscore.js

我的模特是

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数组中删除datatypemetadimension等属性?

2 个答案:

答案 0 :(得分:1)

您可以使用下划线mappick方法非常简洁地执行此操作:

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

答案 1 :(得分:1)

您可以在保存模型之前迭代维度,使用net.uk.sweet建议的pick。 否则,尝试更改此模型的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}
   }
});