如何使用 Lodash 根据键合并两个集合?

48

我有两个集合,对象具有共同的键"userId"。如下:

var _= require('lodash');

var a = [
  { userId:"p1", item:1},
  { userId:"p2", item:2},
  { userId:"p3", item:4}
];

var b = [
  { userId:"p1", profile:1},
  { userId:"p2", profile:2}
];

我希望根据“userId”将它们合并以产生:

[ { userId: 'p1', item: 1, profile: 1 },
  { userId: 'p2', item: 2, profile:2 },
  { userId: 'p3', item: 4 } ]

到目前为止,我有以下这些:

var u = _.uniq(_.union(a, b), false, _.property('userId'));

导致的结果是:

[ { userId: 'p1', item: 1 },
  { userId: 'p2', item: 2 },
  { userId: 'p3', item: 4 },
  { userId: 'p1', profile: 1 },
  { userId: 'p2', profile: 2 } ]

现在我该如何合并它们?

我尝试使用_.keyBy,但结果是:

{ p1: { userId: 'p1', profile: 1 },
  p2: { userId: 'p2', profile: 2 },
  p3: { userId: 'p3', item: 4 } }

这是错误的。

我应该做什么最后一步?

6个回答

60

第二高票答案没有进行正确合并。如果第二个数组包含唯一属性,它将不被考虑。

这种方法可以进行正确的合并。

Lodash

var a = [
  { userId:"p1", item:1},
  { userId:"p2", item:2},
  { userId:"p3", item:4}
];

var b = [
  { userId:"p1", profile:1},
  { userId:"p2", profile:2},
  { userId:"p4", profile:4}
];
var merged = _.merge(_.keyBy(a, 'userId'), _.keyBy(b, 'userId'));
var values = _.values(merged);
console.log(values);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

ES6+

// from https://dev59.com/p14c5IYBdhLWcg3wa52M#34749873
const mergeDeep = (target, ...sources) => {
  if (!sources.length) return target;
  const source = sources.shift();

  if (target instanceof Object && source instanceof Object) {
    for (const key in source) {
      if (source[key] instanceof Object) {
        if (!target[key]) Object.assign(target, { [key]: {} });
        mergeDeep(target[key], source[key]);
      } else {
        Object.assign(target, { [key]: source[key] });
      }
    }
  }

  return mergeDeep(target, ...sources);
}

const a = [
  { userId:"p1", item:1},
  { userId:"p2", item:2},
  { userId:"p3", item:4}
];

const b = [
  { userId:"p1", profile:1},
  { userId:"p2", profile:2},
  { userId:"p4", profile:4}
];


const aKeyed = a.reduce((acc, cur) => ({ ...acc, [cur.userId]: cur }), {});
const bKeyed = b.reduce((acc, cur) => ({ ...acc, [cur.userId]: cur }), {});
const merged = mergeDeep(aKeyed, bKeyed);
const values = Object.values(merged);
console.log(values);


1
这种方法可能并不适用于所有情况,如果userId字段在集合中不是唯一的,则数据会被压缩成一个单一的对象。 - karloluis
@karloluis 那就使用一个唯一的字段? - Neeraj

43
你可以使用 _.map()_.assign()_.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);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.1.0/lodash.min.js"></script>
<pre id="result"></pre>


20
如果第二个列表包含唯一的userId,它将不会被添加到最终列表中。我怀疑这是操作者不想要的行为。 - Undrium
1
这些函数现在在最新版本的JS中可用。a.map(obj => Object.assign(obj, b.find(user => obj.userId === user.userId))) - Tushar

9
Lodash有一个“merge”方法,可用于对象(具有相同键的对象被合并)。在此演示中,首先将数组a和b转换为对象(其中userId是键),然后合并,最后将结果转换回数组(_.values)(去掉键)。由于_.values添加了额外的数组级别,因此需要使用_.flatten。
var u= _({}) // Start with an empty object
  .merge(
    _(a).groupBy("userId").value(),
    _(b).groupBy("userId").value()
  )
  .values()
  .flatten()
  .value();

6
仅供完整性说明:一份不使用任何库的提案。

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('<pre>' + JSON.stringify(c, 0, 4) + '</pre>');


4

没有使用lodash的ES6+版本。

 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('<pre>' + JSON.stringify(result, 0, 2) + '</pre>');   


2

尝试使用此演示

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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接