问题描述
我有两个集合(菜单和订单)
I have two collections (Menu and Orders)
菜单集合包含 Item 对象数组
Menu collection contains array of Item objects
[{'id': '1', 'name': 'apple'}, {'id': '2', 'name': 'orange'}]
并且订单集合还包含Item对象数组
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]
推荐答案
假设您的集合是 Backbone 集合
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}]);
您可以利用在集合上代理的函数和 collection.get
:
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());
});
还有一个可以玩的小提琴 http://jsfiddle.net/bs6jN/
And a Fiddle to play with http://jsfiddle.net/bs6jN/
这篇关于我如何使用 UnderscoreJS 通过它们的“id"联合/合并两个集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!