I have an array of objects that contains duplicates. I need to remove the duplicate while keeping the nested items objects.
To make it clear, this is what my source array looks like:
const src = [
{
id: '5f10b85e145d7163d818066e',
name: 'Product 1',
vendor: 'Vendor 1',
instances: [
{
id: '5f10b8f6145d7163d8180672',
operatingSystem: 'Microsoft Windows 2016',
environment: 'Prod',
version: '4.0',
notes: '',
},
],
},
{
id: '5f10b856145d7163d818066d',
name: 'Product 1',
vendor: 'Vendor 2',
instances: [
{
id: '5f10b8c5145d7163d8180671',
operatingSystem: 'Microsoft Windows 2012R2',
environment: 'Prod',
version: '4.1',
notes: '',
},
],
},
{
id: '5f10b85e145d7163d818066e',
name: 'Product 1',
vendor: 'Vendor 1',
instances: [
{
id: '5f10b8f6145d7163d8180672',
operatingSystem: 'Microsoft Windows 2016',
environment: 'Prod',
version: '4.0',
notes: '',
},
],
},
];
Product 1 of Vendor 1 (with the same id) is duplicated.
I need the instances of the duplicates, to be merged with the first item.
The result array should look like this:
const target = [
{
id: '5f10b85e145d7163d818066e',
name: 'Product 1',
vendor: 'Vendor 1',
instances: [
{
id: '5f10b8f6145d7163d8180672',
operatingSystem: 'Microsoft Windows 2016',
environment: 'Prod',
version: '4.0',
notes: '',
},
{
id: '5f10b8f6145d7163d8180672',
operatingSystem: 'Microsoft Windows 2016',
environment: 'Prod',
version: '4.0',
notes: '',
},
],
},
{
id: '5f10b856145d7163d818066d',
name: 'Product 1',
vendor: 'Vendor 2',
instances: [
{
id: '5f10b8c5145d7163d8180671',
operatingSystem: 'Microsoft Windows 2012R2',
environment: 'Prod',
version: '4.1',
notes: '',
},
],
},
];