user1076813
user1076813

Reputation: 487

Merging two backbone collection and models into one object using underscore

I have two backbone collections Categories and Items, Categories contains category models with id, name, and items (w/c contains item ids in string format separated by commas) and Items collection that contains item models(id, name, etc.).

How do I merge them into one object that can be easily be rendered in a handlebars template

Sample Structure:

var Categories = [{'id':'1', 'category_name':'Burgers', 'category_items':'1,2'},{'id':'2','category_name':'Drinks','category_items':'3'}];

var Items = [{'id':'1','item_name':'Burger 1'},{'id':'1','item_name':'Burger 2'},{'id':'1','item_name':'Chicken; 1'}];

Sample Output:

var output = [{'id':'1', 'category_name':'Burgers', 'items':[{'id':'1','item_name':'Burger1', ...},{'id':'1','item_name':'Burger2', ...} ]}, {'id':'2', 'category_name':'Chicken', 'items':[{'id':'3','item_name':'Chicken1', ...} ]

And yes, i tried enough, but I can't seem to manage it

Upvotes: 2

Views: 3014

Answers (2)

Loamhoof
Loamhoof

Reputation: 8293

Relying on Underscore's helpful functions:

var json = _.map(c.toJSON(), function(c) {
  return _.extend(c, {
    category_items: _.map(c.category_items.split(','), function(id)                 {
      return i.get(id).toJSON();
    })
  });
});

http://jsfiddle.net/626x9/1/

The first _.map coupled with _.extend just serves the purpose on replacing the category_items. I find it quite abusive, but can't remember if there's any method that would do that in one shot.

Upvotes: 1

Chickenrice
Chickenrice

Reputation: 5727

I write a function called "mergeObjectWithId". It merge data from two collection follow these step:

  1. Using collection.findWhere() to get the target model which need to merge.
  2. Using collection.where() to get the models in item collection.
  3. Then assign the items array to target object's property items. Now you get the output object which you wanted.

Try this function:

function mergeObjectWithId(id){
  //assume categories is your Category collection instance
  var obj = categories.findWhere({id:id}).clone();
  //assume items is your Item collection instance
  obj.items = items.find({id:id}).slice(0);
  return obj;
}

var output = mergeObjectWithId(1);

Hope this is helpful for you.

Upvotes: 1

Related Questions