How to Flatten an Array of Objects in JavaScript

JavaScript Array flat() method flattens an array of Objects and returns a flattened array of Objects.

Syntax

Array.flat(argument)

Parameters

It is several levels at which level you want to flatten an object.

Example

Let’s say 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.