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

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

    ES6+ version without lodash.

     const array1 = [{ userId: "p1", item: 1 },  { userId: "p2", item: 2 },{ userId: "p3", item: 4 }];
    const array2 = [{ userId: "p1", profile: 1 }, { userId: "p2", profile: 2 }];
    
    
    const result = array1.map(a => ({
      ...a,
      ...array2.find(b => b.userId === a.userId) // _.find(array2, 'skuId') <-- or with lodash 
    }));
    
     document.write('
    ' + JSON.stringify(result, 0, 2) + '
    ');

提交回复
热议问题