0

My model is

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

I have a model instance named storageInfo filled with

{
    "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"}
    ]
}

but before sending to the server I want the model to be like this:

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

How can I remove attributes like q_text, datatype and meta from the dimension array of my model?

1
  • 1
    Careful with mutable objects in defaults, the references are copied into new models as needed rather than cloned so your dimension array is subject to surprising reference sharing. defaults: function() { return { ... } } is a better approach in such cases. Commented Mar 4, 2014 at 18:06

2 Answers 2

1

You can use the underscore map and pick methods to do this quite succinctly:

storageInfo.dimensions = _.map(storageInfo.dimensions, function(obj) {
    return _.pick(obj, 'p_id', 'answer');
});
Sign up to request clarification or add additional context in comments.

Comments

1

You may iterate through the dimensions before saving the model, using pick as suggested by net.uk.sweet. Otherwise, try to change the toJSON method of this model so it always returns the fields you would prefer:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.