Используйте поток для создания функции.Объедините массивы в один массив, сгруппируйте их по 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>