Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

backbone.js

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

like image 926
rkw Avatar asked Aug 16 '11 08:08

rkw


2 Answers

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') })
like image 110
rkw Avatar answered Nov 06 '22 15:11

rkw


Cleaner still:

_.invoke(Cards.filter(...), 'get', 'value')
like image 42
dzuc Avatar answered Nov 06 '22 16:11

dzuc