1

I want to compare model attributes from my collection and store it to a new model.

Collection:
   Model1:
     Apple: 1
     Banana: 0
     Orange: 0
     Status: 1254869
   Model2:
     Apple: 0
     Banana: 1
     Orange: 1
     Status: null

The output should be:

ModelResult:
     Apple: 1
     Banana: 1
     Orange: 1
     Status: 1254869

Any ideas?

I'm doing it manually

ModelResult = collection.at(0); 
collection.each( function(model){
    if(model.get("Apple") != 0){
      ModelResult.set({Apple: model.get("Apple")});
    }
    if(model.get("Banana") != 0){
      ModelResult.set({Apple: model.get("Banana")});
    }
    if(model.get("Orange") != 0){
      ModelResult.set({Apple: model.get("Orange")});
    }
    if(model.get("Status") != ""){
      ModelResult.set({Apple: model.get("Status")});
    }
});

NOTE:

Is it possible to also eliminate 0 or null values on ModelResult?

Thank you.

n0minal
  • 3,195
  • 9
  • 46
  • 71

1 Answers1

1

For eliminating 0 and null values you can use the validate function. It is called always before set or save is called and if the valus don't match what you want you just return an error message and the changes won't take effect.

This also means your ModelResult has to be a separate model.

var ModelResult = Backbone.Model.extend({
  ...
  validate: function(attrs) {
    if (_.intersection([0, null], _.values(attrs))) {
      return "Zeroes and nulls are ignored.";
    }
  },
  ...
});

Now your each function could be like

function(model) {
  _.each(model.toJSON(), function(value, key) {
    ModelResult.set(key, value);
  }); 
}

Now all it will iterate through every model's every attribute and add them to the ModelResult, but filtering out all 0s and nulls.

Hope this helps!

jakee
  • 18,486
  • 3
  • 37
  • 42