Last Updated: February 25, 2016
·
793
· havvg

Use map-reduce to create Collection from existing select

Assuming you got a <select> with <option value="5"> where the value of each option is the id of the model to create the collection for.

$options represents the jQuery selection, e.g. in a View: $('select.products', this.$el).find('option');

var products = _.reduce($options.map(function() {
    var id = $(this).val();
    if (!id) {
        return false;
    }

    var product = new Product({
        id: id
    });
    product.fetch();

    return product;
}), function(collection, product) {
    if (product) {
        collection.add(product);
    }

    return collection;
}, new ProductCollection());