我能够用lodash合并存储在数组中的对象,但我需要的是找到一种基于作为对象一部分的键进行合并的方法。如果我不使用密钥,则合并是不可靠的,因为当文档无序返回时,它将创建无效的合并。因此,希望有一种在我的情况下基于键值进行合并的方法
这是一些样品 Doc 1
[
{
"id": 123,
"Key1": "Test 1",
"Key3": "Test 0"
},
{
"id": 456,
"Key1": "Test 2",
"Key2": "Test 3"
}
]
文档2 [
{
"id": 123,
"Key2": "Test 7",
"Key3": "Test 8"
},
{
"id": 789,
"Key1": "Test 5",
"Key2": "Test 6"
}
]
基于上面的简单示例,我正在寻找这样的输出
[
{
"id": 123,
"Key1": "Test 1",
"Key2": "Test 7",
"Key3": "Test 8"
},
{
"id": 456,
"Key1": "Test 2",
"Key2": "Test 3"
},
{
"id": 789,
"Key1": "Test 5",
"Key2": "Test 6"
}
]
答案 0 :(得分:0)
const addKeys = (results, keys) => keys.reduce(
(final, item) => {
const id = item.id;
let current = final.find(i => i.id === id);
if (!current) {
current = { id: id };
final.push(current);
}
Object.keys(item).forEach(key => { current[key] = item[key] });
return final;
}, results
);
console.log(addKeys(
[
{
"id": 123,
"Key1": "Test 1",
"Key3": "Test 0"
},
{
"id": 456,
"Key1": "Test 2",
"Key2": "Test 3"
}
],
[
{
"id": 123,
"Key2": "Test 7",
"Key3": "Test 8"
},
{
"id": 789,
"Key1": "Test 5",
"Key2": "Test 6"
}
]
));
答案 1 :(得分:0)
使用流程创建函数。将数组连接为单个数组,按id
进行分组,然后映射组,然后将每个组合并到单个对象:
const { flow, concat, partialRight: pr, groupBy, map, merge } = _
const mergeArrays = flow(
concat, // concat to a single array
pr(groupBy, 'id'), // group item by id
pr(map, g => merge({}, ...g)) // merge each group to a single object
)
const arr1 = [{"id":123,"Key1":"Test 1","Key3":"Test 0"},{"id":456,"Key1":"Test 2","Key2":"Test 3"}]
const arr2 = [{"id":123,"Key2":"Test 7","Key3":"Test 8"},{"id":789,"Key1":"Test 5","Key2":"Test 6"}]
const result = mergeArrays(arr1, arr2)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
此解决方案的简化版本带有lodash/fp:
const { flow, concat, groupBy, map, mergeAll } = _
const mergeArrays = flow(
concat, // concat to a single array
groupBy('id'), // group item by id
map(mergeAll) // merge each group to a single object
)
const arr1 = [{"id":123,"Key1":"Test 1","Key3":"Test 0"},{"id":456,"Key1":"Test 2","Key2":"Test 3"}]
const arr2 = [{"id":123,"Key2":"Test 7","Key3":"Test 8"},{"id":789,"Key1":"Test 5","Key2":"Test 6"}]
const result = mergeArrays(arr1, arr2)
console.log(result)
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>