Search code examples
javascriptbackbone.jsunderscore.jsjavascript-objects

How do I union/merge two Collections by their 'id' using UnderscoreJS


I have two collections (Menu and Orders)

Menu collection contains array of Item objects

[{'id': '1', 'name': 'apple'}, {'id': '2', 'name': 'orange'}]

And Orders collection also contains array of Item objects

[{'id': '1', 'quantity': '0'}]

And I want them merged together their attributes by ID into another collection (this is needed for templating purposes only):

[{'id': '1', 'name': 'apple', 'quantity': '1'}, {'id': '2', 'name': 'orange'}]

Is there a underscore method on this or I need to define a function for this? [it seems i tried all merging functions on underscore but none of them works the way I expected]


Solution

  • Assuming your collections are Backbone collections

    var menus = new Backbone.Collection([
        {'id': '1', 'name': 'apple'}, 
        {'id': '2', 'name': 'orange'}
    ]);
    
    var orders = new Backbone.Collection([{'id': '1', 'quantity': 1}]);
    

    you can take advantage of the functions proxied on collections and of collection.get :

    var merged = menus.map(function(menu) {
        var id = menu.get('id'),
            order = orders.get(id);
    
        if (!order) return menu.toJSON();
    
        return _.extend(menu.toJSON(), order.toJSON());
    });
    

    And a Fiddle to play with http://jsfiddle.net/bs6jN/