rkw
rkw

Reputation: 7297

How do you .pluck() values from a Collection after you .filter() it?

window.CardList = Backbone.Collection.extend(...);

var Cards = new CardList;

Cards.filter(...).pluck('values')

Is there a clean way to filter a collection and then pluck the values? The only work around I know is to reinitialize the collection:

new CardList(Cards.filter(...)).pluck('values')

OR to map the output after it's been filtered:

Cards.filter(...).map(...)

which seems weird since it has a perfectly good .pluck() method

Upvotes: 5

Views: 4781

Answers (3)

dzuc
dzuc

Reputation: 760

Cleaner still:

_.invoke(Cards.filter(...), 'get', 'value')

Upvotes: 4

rkw
rkw

Reputation: 7297

CardList a backbone collection, once it is filtered or pluck'ed, it becomes an array of backbone models.

An array of backbone models cannot be pluck'ed again, unless you wrap it in another backbone collection (which is what the original post mentioned)

Alternative ways are:

  1. Wrap it with underscore and chain it: _(Cards.filter(...)).chain().pluck('attributes').pluck('value').value()

  2. Just map out the value (I ended up using this solution, it was the cleanest in the end):

_.map(Cards.filter(...), function(m) { return m.get('value') })

Upvotes: 6

ant_Ti
ant_Ti

Reputation: 2425

Cards.pluck.call({models: Cards.filter(...)}, 'values');

Upvotes: 0

Related Questions