简体   繁体   English

如何使用UnderscoreJS通过'id'联合/合并两个集合

[英]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 菜单集包含Item对象的数组

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

And Orders collection also contains array of Item objects Orders集合还包含Item对象的数组

[{'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将它们的属性合并到另一个集合中(这仅用于模板目的):

[{'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] [似乎我在下划线上尝试了所有合并函数,但它们都没有按我预期的方式工作]

Don't think there is a function defined in underscore.js for this but one way to do it is by using the _.map and _.find functions as follows, 不要认为在underscore.js中定义了一个函数,但是一种方法是使用_.map_.find函数,如下所示,

var menus = [{'id': '1', 'name': 'apple'}, {'id': '2', 'name': 'orange'}];

var orders = [{'id': '1', 'quantity': '0'}];

var newMenu = _.map(menus, function (menu) {  
    var order = _.find(orders, function (o) { 
        return o.id == menu.id;
    }); 
    return _.extend(menu, order); 
});

console.log(newMenu);

This should do the job: 这应该做的工作:

var result = [];
_.each(menu, function(el){
    _.extend(el,_.where(orders, {id: el.id})[0] || {});
    result.push(el);
});

Assuming your collections are Backbone collections 假设您的收藏品是Backbone收藏品

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 : 您可以利用集合和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/ http://jsfiddle.net/bs6jN/一起玩的小提琴

If it is an union you want to do, you can do it using the underscore way: 如果它是你想要的联盟,你可以使用下划线方式:

// collectionUnion(*arrays, iteratee)
function collectionUnion() {
    var args = Array.prototype.slice.call(arguments);
    var it = args.pop();

    return _.uniq(_.flatten(args, true), it);
}

It just an improvment of the original function _.union(*arrays) , adding an iteratee to work collection (array of object). 它只是原始函数_.union(*arrays)的改进,将_.union(*arrays)添加到工作集合(对象数组)。

Here how to use it: 在这里如何使用它:

var result = collectionUnion(a, b, c, function (item) {
    return item.id;
});

The original function which is just working with array, looks like that: 正在使用数组的原始函数看起来像这样:

_.union = function() {
  return _.uniq(flatten(arguments, true, true));
};

And in bonus a full example: 在奖金中有一个完整的例子:

// collectionUnion(*arrays, iteratee)
function collectionUnion() {
    var args = Array.prototype.slice.call(arguments);
    var it = args.pop();

    return _.uniq(_.flatten(args, true), it);
}

var a = [{id: 0}, {id: 1}, {id: 2}];
var b = [{id: 2}, {id: 3}];
var c = [{id: 0}, {id: 1}, {id: 2}];

var result = collectionUnion(a, b, c, function (item) {
    return item.id;
});

console.log(result); // [ { id: 0 }, { id: 1 }, { id: 2 }, { id: 3 } ]

EDIT: I wrote a blog post if you want more details: http://geekcoder.org/union-of-two-collections-using-underscorejs/ 编辑:如果你想了解更多细节,我写了一篇博客文章: http//geekcoder.org/union-of-two-collections-using-underscorejs/

We ca merge with plain js like this 我们可以像这样与普通的js合并

    var arrOne = [{'id': '1', 'name': 'apple'}, {'id': '2', 'name': 'orange'}];
    var arrTwo = [{'id': '1','quantity': '0'}];

    function mergeArr(arrOne, arrTwo) {
        var mergedArr = [];
        arrOne.forEach(function (item) {
            var O = item;
            arrTwo.forEach(function (itemTwo) {
                if (O.id === itemTwo.id) {
                    O.quantity = itemTwo.quantity;

                }
            });
            mergedArr.push(O);

        });

        return mergedArr;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 不使用underscoreJS怎么办? - how can I do this without using underscoreJS? 如何使用underscoreJS连接两个数组的值 - How to join values of two arrays using underscoreJS 使用Underscorejs按位置合并两组js对象 - Merge two sets of js object by their positions using Underscorejs 如何合并两个 mongo collections? - How can I merge two mongo collections? 如何合并两个几乎相同的数组/对象(使用underscorejs或类似的库)? - How to merge two almost identical arrays/objects (with underscorejs or similiar libary)? 如何根据文档中的参考ID合并并观察Firestore中的两个集合? - How to merge and observe two collections in Firestore based on reference ID in documents? 如何在 TypeScript 中合并两个具有共享 ID 的对象 arrays? - How do I merge two arrays of Objects with a shared ID in TypeScript? 如何使用UnderscoreJS进行讨论? - How to do currying with UnderscoreJS? 如何使用Javascript / underscorejs找到包含对象的数组数组的交集? - How do I find the intersection of an array of arrays that contain objects using Javascript/underscorejs? 如何在monogo数据库中删除两个集合中存在相同ID的记录? - How do I delete a record with same id present in two collections in monogo database?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM