How to Flatten a Deeply Nested Array of Objects in JavaScript?

Learn how to flatten a deep nested array of objects in JavaScript

Let's suppose you have the following array of deeply nested objects that you wish to flatten:

const users = [
    [{ id: 1, name: 'John' }, { id: 3, name: 'Wayne' }],
    [
        [
            { id: 7, name: 'Melissa' },
            { id: 2, name: 'David' }
        ],
    ],
];

In the array above, the first element is only one-level deep, while the second element is two-levels deep.

You can simply use the Array.prototype.flat() method to flatten the array. For example, to flatten it completely, regardless of how ever many levels deep the array is, you can do the following:

// ES2019+
const flattened = users.flat(Infinity);

console.log(flattened);

/* [
    { id: 1, name: 'John' },
    { id: 3, name: 'Wayne' },
    { id: 7, name: 'Melissa' },
    { id: 2, name: 'David' },
] */

If you wish to only flatten the array to a specific nesting level, then you may specify it as the first argument to the Array.prototype.flat() method, for example, like so:

// ES2019+
const flattened = users.flat(4); // flatten array 4-levels deep

console.log(flattened);

/* [
    { id: 1, name: 'John' },
    { id: 3, name: 'Wayne' },
    { id: 7, name: 'Melissa' },
    { id: 2, name: 'David' },
] */

If you don't specify any arguments to the Array.prototype.flat() method, by default it will flatten only one-level deep. For example:

// ES2019+
const flattened = users.flat();

console.log(flattened);

/* [
    { id: 1, name: 'John' },
    { id: 3, name: 'Wayne' },
    [ { id: 7, name: 'Melissa' }, { id: 2, name: 'David' } ],
] */

If you do not support ES2019 yet, then you can use other backward compatible ways to flatten an array.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.