Anar Anar -4 years ago 63
Javascript Question

How to find a model from a collection according to some attribute other than the ID?

I have a model with several object:

Friend = Backbone.Model.extend({
//Create a model to hold friend attribute
name: null,

var f1 = new Friend({ name: "Lee" });
var f2 = new Friend({ name: "David"});
var f3 = new Friend({ name: "Lynn"});

and also, I will add these friends object to a collection:

Friends = Backbone.Collection.extend({
model: Friend,


and now I want to get a model according to the name of the Friend. I know that I can add an
attribute to achieve this. But I think there should have some more simple way to do this.

Answer Source

Backbone collections support the underscorejs find method, so using that should work.

things.find(function(model) { return model.get('name') === 'Lee'; });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download