I have two collections, and the objects have a common key \"userId\". As below:
var _= require(\'lodash\');
var a = [
{ userId:\"p1\", item:1},
{ userId
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) + '
');