问题描述
我有两个集合(菜单和命令)
I have two collections (Menu and Orders)
菜单集包含项目对象的数组
[{'id': '1', 'name': 'apple'}, {'id': '2', 'name': 'orange'}]
和订单收集也包含项目对象的数组
And Orders collection also contains array of Item objects
[{'id': '1', 'quantity': '0'}]
和我要他们合并在一起,通过ID其属性为另一个集合(这是需要仅模板目的):
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]
推荐答案
假设你的藏品都是骨干集合
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());
});
和一拨弄
这篇关于我怎么工会/使用UnderscoreJS他们的'身份证'合并两个集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!