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

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

    Try this 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
    }];
    
    a.forEach(function (aitem) {
        b.forEach(function (bitem) {
            if(aitem.userId === bitem.userId) {
                _.assign(aitem, bitem);
            }
        });
    });
    
    console.log(a);
    

提交回复
热议问题