Where filtering in backbone

Was doing some filtering on a collection and came across a problem where I wanted to have a variable as the key in ‘where’ but it wouldn’t take and I wasn’t sure why. Stack Overflow to the rescue! http://stackoverflow.com/questions/27732629/backbonejs-variable-in-a-where-filter-key/27732713 So it turns out that it doesn’t work because  the key “prop” is always interpreted literally, as a string (and no property in my collection is ‘prop’). So to get around it you use something like this instead of using what I was originally doing:

var newCollection = function(myCollection,prop,val){

alert('myprop: ' + prop);
alert('val: ' + val);

var results = myCollection.where({
  //prop: val this doesn't work even if I put a string above it to make sure the value coming through is fine
  //prop: "Glasnevin" //this doesn't work     
  "location" : val //this works


Instead you use:

var results = myCollection.where(_.object([prop], [val]));

or alternatively (as also suggested by the kind people on stackoverflow)

var where = {};
where[prop] = val;

var results = myCollection.where(where);

One to keep in the back pocket I suspect!