xchrisbradley
xchrisbradley

Reputation: 503

JavaScript combine original object with sub array of objects

I have an large array of objects with some keys:values, one of the keys has a value that is an array of objects. I want to reduce the subarray into a new array of objects.

I can't figure out a solution using mapping thus far.

const warehouse = [
    {
        Server: 'EU',
        Department: 'Paper',
        Suppliers: [
            {
                Name: 'EU Paper',
                Contract: 'Active'
            },
            {
                Name: 'Local Tree',
                Contract: 'Ended'
            }
        ]
    },
    {
        Server: 'US',
        Department: 'Steel',
        Suppliers: [
            {
                Name: 'Steel Research',
                Contract: 'Active'
            },
            {
                Name: 'Heat Vantage',
                Contract: 'Active'
            }
        ]
    }
]

Output should be

const suppliers = [
    {
        Server: 'EU',
        Department: 'Paper',
        Name: 'EU Paper',
        Contract: 'Active'
    },
    {
        Server: 'EU',
        Department: 'Paper',
        Name: 'Local Tree',
        Contract: 'Ended'
    },
    {
        Server: 'US',
        Department: 'Steel',
        Name: 'Steel Research',
        Contract: 'Active'
    },
    {
        Server: 'US',
        Department: 'Steel',
        Name: 'Heat Vantage',
        Contract: 'Active'
    },
]

I can do this with basic JavaScript but i would like to see an option that optimizes for performance

Upvotes: 0

Views: 849

Answers (1)

Eddie
Eddie

Reputation: 26844

You can use flatMap to loop thru the array and flat the result. Use map to loop thru the Suppliers array.

const warehouse = [{"Server":"EU","Department":"Paper","Suppliers":[{"Name":"EU Paper","Contract":"Active"},{"Name":"Local Tree","Contract":"Ended"}]},{"Server":"US","Department":"Steel","Suppliers":[{"Name":"Steel Research","Contract":"Active"},{"Name":"Heat Vantage","Contract":"Active"}]}];

let result = warehouse.flatMap(({Suppliers,...r}) => Suppliers.map(o => ({ ...o,...r})));
console.log(result);

You can also use concat and map

const warehouse = [{"Server":"EU","Department":"Paper","Suppliers":[{"Name":"EU Paper","Contract":"Active"},{"Name":"Local Tree","Contract":"Ended"}]},{"Server":"US","Department":"Steel","Suppliers":[{"Name":"Steel Research","Contract":"Active"},{"Name":"Heat Vantage","Contract":"Active"}]}];

let result = [].concat(...warehouse.map(({Suppliers,...r}) => Suppliers.map(o => ({ ...o,...r}))));
console.log(result);

Upvotes: 5

Related Questions