如何使用 Lodash 基于一个键合并两个集合? [英] How to use Lodash to merge two collections based on a key?
本文介绍了如何使用 Lodash 基于一个键合并两个集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个集合,对象有一个公共键userId".如下:
I have two collections, and the objects have a common key "userId". As below:
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"合并它们来生成:
I want to merge them based on "userId" to produce:
[ { 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 但结果是:
I tried _.keyBy but it results in:
{ p1: { userId: 'p1', profile: 1 },
p2: { userId: 'p2', profile: 2 },
p3: { userId: 'p3', item: 4 } }
这是错误的.
我应该做的最后一步是什么?
What's the last step I should do?
推荐答案
投票第二高的答案没有正确合并.如果第二个数组包含唯一属性,则不考虑.
Second highest voted answer doesn't do proper merge. If second array contains an unique property, it is not taken into account.
这种方法进行了适当的合并.
This approach does a proper merge.
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>
// from https://stackoverflow.com/a/34749873/80766
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);
这篇关于如何使用 Lodash 基于一个键合并两个集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文