I'm struggling with manipulating a Javascript object and will appreciate your advice:
I have the following object:
const source = {
id: '1',
name: 'Customer A',
projects: [
{
id: '10',
name: 'Project 2',
description: 'Project 2 description',
products: [
{
id: '100',
name: 'Product 1',
vendor: 'Vendor 1',
instances: [
{
id: '1000',
operatingSystem: 'Microsoft Windows 2012R2',
environment: 'Prod',
version: '4.1',
notes: '',
},
],
},
{
id: '200',
name: 'Product 2',
vendor: 'Vendor 2',
instances: [
{
id: '2000',
operatingSystem: 'Microsoft Windows 2016',
environment: 'Prod',
version: '4.0',
notes: '',
},
],
},
],
},
{
id: '20',
name: 'Project 1',
description: 'Project 1 description',
products: [
{
id: '200',
name: 'Product 2',
vendor: 'Vendor 2',
instances: [
{
id: '2000',
operatingSystem: 'Microsoft Windows 2016',
environment: 'Prod',
version: '4.0',
notes: '',
},
{
id: '3000',
operatingSystem: 'RedHat Linux 7',
environment: 'Prod',
version: '3.12',
notes: '',
},
],
},
],
},
],
};
I would like to extract from the object above a list of instances grouped by products (this part is working fine):
const products = [
{
id: '100',
name: 'Product 1',
vendor: 'Vendor 1',
instances: [
{
id: '1000',
operatingSystem: 'Microsoft Windows 2012R2',
environment: 'Prod',
version: '4.1',
notes: '',
},
],
},
{
id: '200',
name: 'Product 2',
vendor: 'Vendor 2',
instances: [
{
id: '2000',
operatingSystem: 'Microsoft Windows 2016',
environment: 'Prod',
version: '4.0',
notes: '',
},
{
id: '2000',
operatingSystem: 'Microsoft Windows 2016',
environment: 'Prod',
version: '4.0',
notes: '',
},
{
id: '3000',
operatingSystem: 'RedHat Linux 7',
environment: 'Prod',
version: '3.12',
notes: '',
},
],
},
];
The above is achieved by mapping the projects, flattening the products-array, and reducing the results. My next goal is to add each instance the projects it associated to. I need to attach the project id and project name. In the example above, you can see the instance with the '2000' id is associated with 2 projects, and therefore, the expected results should look like this:
const expected = [
{
id: '100',
name: 'Product 1',
vendor: 'Vendor 1',
instances: [
{
id: '1000',
operatingSystem: 'Microsoft Windows 2012R2',
environment: 'Prod',
version: '4.1',
notes: '',
projects: [
{
id: '10',
name: 'Project 2',
},
],
},
],
},
{
id: '200',
name: 'Product 2',
vendor: 'Vendor 2',
instances: [
{
id: '2000',
operatingSystem: 'Microsoft Windows 2016',
environment: 'Prod',
version: '4.0',
notes: '',
projects: [
{
id: '10',
name: 'Project 2',
},
{
id: '20',
name: 'Project 1',
},
],
},
{
id: '3000',
operatingSystem: 'RedHat Linux 7',
environment: 'Prod',
version: '3.12',
notes: '',
projects: [
{
id: '20',
name: 'Project 1',
},
],
},
],
},
];
I tried to manipulate the array by several 'forEach' loops, maps, and so on but with no success. Would appreciate having your ideas with how it can be achieved.