How to use (find)where in backbone to get a specific field of an array

10,228

Collection.where and Collection.findWhere are convenience functions for simple filters. In your case, you would use the more complex Collection.find (proxied to _.find)

find _.find(list, iterator, [context])
Looks through each value in the list, returning the first one that passes a truth test (iterator). The function returns as soon as it finds an acceptable element, and doesn't traverse the entire list.

And if I understand correctly your condition, it could look like

MyCollection.find(function(model) {
    return _.findWhere(model.get('Group'), {id: 34});
})
Share:
10,228
Ludo
Author by

Ludo

Updated on June 04, 2022

Comments

  • Ludo
    Ludo almost 2 years

    I use to use the where method from the Collections in backbone. But I don't see how to fetch this result:

    MyCollection.Group[x].id
    

    As you can guess, MyCollection is the collection, Group is an array, and id is the field I would like to match for a specific value, something like:

    MyCollection.findWhere(Group[x].id: 34);
    

    I have seen the "contains" function of underscore but it doesn't seems to work with associative arrays

    Is there a way to do it or should we parse the collection manually using Javascript ?

  • Ludo
    Ludo almost 11 years
    Are you sure it's not only for the DOM ? I get a TypeError: Cannot read property 'nodeType' of undefined trying to call $(MyCollection).find({ Group: { id: 34 }});
  • ylerjen
    ylerjen almost 8 years
    jQuery's .find() is only for the DOM. $.grep() would be the jQuery's correct answer.