Last Updated: February 25, 2016
·
999
· 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());

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside