How to flatten Array of Objects in JavaScript

To flatten an Array of Objects in JavaScript, use the Array.flat() function. The flat() is a built-in JavaScript 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 we 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 it is 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' }
]

Another case is that if you don’t declare an argument, then it will take 1 as default and flatten only the first level of the Array.

const flattenedArray = users.flat();
console.log(flattenedArray);

Output

[
   { id: 1, name: 'Alice' },
   { id: 3, name: 'Bob' }, 
   [ { id: 7, name: 'Calvin' }, { id: 2, name: 'Doe' } ]
]

Conclusion

With the help of this easy syntax and examples, I hope that you will have understood how to Flatten an Array in JavaScript and how we can use Arguments to Flatten the Array at Different Levels.

That’s it for this tutorial.

Leave a Comment