Вот решение, которое не использует библиотеки, но оно не динамическое, поэтому оно адаптировано только для вашего случая использования.
Я заблокирован и не смог сделать его более оптимальным, поэтому любая обратная связьможно только приветствовать:)
const origin = {
allTest: [
{
testName: 'A',
platform: [{ name: 'chrome', area: ['1'] }],
},
{
testName: 'B',
platform: [{ name: 'Edge', area: ['2'] }],
},
],
}
const updated = {
allTest: [
{
testName: 'A',
platform: [{ name: 'chrome', area: ['1'] }],
},
{
testName: 'B',
platform: [{ name: 'Safari', area: ['3'] }],
},
{
testName: 'C',
platform: [{ name: 'IE', area: ['4'] }],
},
],
}
const findAndMergePlatforms = (array, item) =>
array
.filter(o => o.testName === item.testName)
.map(o => ({ ...o, platform: [...o.platform, ...item.platform] }))
const removeExisting = (array, item) =>
array.filter(o => o.testName !== item.testName)
const removeDuplicatePlatforms = platforms =>
platforms.reduce(
(acc, curr) =>
acc.filter(({ name }) => name === curr.name).length > 0
? acc
: [...acc, curr],
[]
)
const mergedAllTests =
// Merge "allTest" objects from both arrays
[...origin.allTest, ...updated.allTest]
// Merge the "platform" properties
.reduce((acc, curr) => {
const found = findAndMergePlatforms(acc, curr)
acc = removeExisting(acc, curr)
return found.length !== 0 ? [...acc, ...found] : [...acc, curr]
}, [])
// Remove platform duplicates
.map(({ testName, platform }) => ({
testName,
platform: removeDuplicatePlatforms(platform),
}))
const result = { allTest: mergedAllTests }
const util = require('util')
console.log(util.inspect(result, { showHidden: false, depth: null }))
Редактировать: Добавлены комментарии и исправлен результат, включающий allTest
объект.