lorless
lorless

Reputation: 4478

How to get models from a collection that have a certain attribute

I'd like to get some models in my collection that have the attribute unit. My current method involves this,

        var unitIds = ciLocal.where({unit: !null});
        console.log(unitIds.length);

The weird thing is that removing ! returns 58 (the total minus those that unit is not null) values while the code above returns 0.

Can anyone suggest a good way to loop my collection and return those models that have anything in unit?

Its probably worth mentioning that unit contains two values, one being unitID and the other being an array of more values. I need to get the whole model back and not just the unit section.

In this screenshot you can see that 68 has null while 69 has object. enter image description here

{"carID":"37","unit":{"unitID":"37_Chaffinch_75","positionHistory":[{"lat":"51.474312","long":"-0.491672","time":"2011-07-08 11:24:47","status":"1","estimatedSpeed":"0","lastSoundFileName":"Car park Exit","lastSoundRange":"10","lastSoundTime":"2011-07-08 11:25:03","isToday":false,"minutesAgo":1028188}]},"registration":"CJ-361-YG","color":"Luxor","phone":"","model":"SDV8"}

Upvotes: 1

Views: 1302

Answers (1)

nikoshr
nikoshr

Reputation: 33334

You can use _.filter on your collection to specify a custom validation function.

filter _.filter(list, iterator, [context])
Looks through each value in the list, returning an array of all the values that pass a truth test (iterator).

Something like this should keep the models with a defined, non null value

var c = new Backbone.Collection([
    {id: 1, unit: 1},
    {id: 2, unit: null},
    {id: 3}
]);

c.filter(function(model) {
    var v = model.get('unit');
    return ((typeof(v)!=='undefined') && (v!==null));
})

And a demo http://jsfiddle.net/nikoshr/84L2R/

Upvotes: 3

Related Questions