To flatten an Array of Objects in JavaScript, you can use the “Array.prototype.flat()” function. The flat() is a built-in array function that flattens an array of Objects and returns a flattened array of Objects.
Syntax
Array.flat(argument)
Arguments
It is several levels at which level you want to flatten an object.
Example
We have an array of nested objects and need to flatten that Array.
const users = [
[{ id: 1, name: 'Alice' }, { id: 3, name: 'Bob' }],
[
[
{ id: 7, name: 'Calvin' },
{ id: 2, name: 'Doe' }
],
],
];
To flatten this Array of objects, use Infinity as an argument to the flat() function.
const flattenedArray = users.flat(Infinity);
console.log(flattenedArray);
Output
[
{ id: 1, name: 'Alice' },
{ id: 3, name: 'Bob' },
{ id: 7, name: 'Calvin' },
{ id: 2, name: 'Doe' }
]
Here, we took Infinity as an argument; it will flatten all the objects at a base level, No matter how deeply Nested.
So, if you want to flatten the Array on some predefined level, you can declare that as an argument.
Let’s take an example of a custom-defined argument.
const flattenedArray = users.flat(3);
console.log(flattenedArray);
Output
[
{ id: 1, name: 'Alice' },
{ id: 3, name: 'Bob' },
{ id: 7, name: 'Calvin' },
{ id: 2, name: 'Doe' }
]
That’s it.

Niva Shah is a Software Engineer with over eight years of experience. She has developed a strong foundation in computer science principles and a passion for problem-solving.