Merging two backbone collection and models into one object using underscore

廉价感情. 提交于 2019-12-11 00:57:35

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/17314370/merging-two-backbone-collection-and-models-into-one-object-using-underscore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!