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

前端 未结 6 1828
谎友^
谎友^ 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:56

    You can use _.map(), _.assign() and _.find().

    // Iterate over first array of objects
    _.map(a, function(obj) {
    
        // add the properties from second array matching the userID
        // to the object from first array and return the updated object
        return _.assign(obj, _.find(b, {userId: obj.userId}));
    });
    

    Fiddle Demo

    var a = [{
        userId: "p1",
        item: 1
    }, {
        userId: "p2",
        item: 2
    }, {
        userId: "p3",
        item: 4
    }];
    
    var b = [{
        userId: "p1",
        profile: 1
    }, {
        userId: "p2",
        profile: 2
    }];
    
    var arrResult = _.map(a, function(obj) {
        return _.assign(obj, _.find(b, {
            userId: obj.userId
        }));
    });
    
    console.log(arrResult);
    document.getElementById('result').innerHTML = JSON.stringify(arrResult, 0, 4);
    
    

提交回复
热议问题