我有两个集合,对象有一个公共密钥“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 } }
这是错的.
我应该做的最后一步是什么?
解决方法:
您可以使用_.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}));
});
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>