How to use (find)where in backbone to get a specific field of an array
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});
})
Ludo
Updated on June 04, 2022Comments
-
Ludo almost 2 years
I use to use the
where
method from theCollections
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, andid
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 arraysIs there a way to do it or should we parse the collection manually using Javascript ?
-
Ludo almost 11 yearsAre 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 almost 8 yearsjQuery's
.find()
is only for the DOM.$.grep()
would be the jQuery's correct answer.