0

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

1 Answer 1

5

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);

Sign up to request clarification or add additional context in comments.

4 Comments

The second option works for me. I'm interested in the first one but .flatMap is not a method for me?
As per doc, flatMap is compatible with Nodejs 11.
..Or you can use Polyfill

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.