How to use Lodash to merge two collections based on a key?

前端 未结 6 1836
谎友^
谎友^ 2020-12-08 07:34

I have two collections, and the objects have a common key \"userId\". As below:

var _= require(\'lodash\');

var a = [
  { userId:\"p1\", item:1},
  { userId         


        
6条回答
  •  情话喂你
    2020-12-08 07:57

    Just for completeness: A proposal without any library.

    function merge(a, b, key) {
    
        function x(a) {
            a.forEach(function (b) {
                if (!(b[key] in obj)) {
                    obj[b[key]] = obj[b[key]] || {};
                    array.push(obj[b[key]]);
                }
                Object.keys(b).forEach(function (k) {
                    obj[b[key]][k] = b[k];
                });
            });
        }
    
        var array = [],
            obj = {};
    
        x(a);
        x(b);
        return array;
    }
    
    var a = [
            { userId: "p1", item: 1 },
            { userId: "p2", item: 2 },
            { userId: "p3", item: 4 }
        ],
        b = [
            { userId: "p1", profile: 1 },
            { userId: "p2", profile: 2 }
        ],
        c = merge(a, b, 'userId');
    
    document.write('
    ' + JSON.stringify(c, 0, 4) + '
    ');

提交回复
热议问题