JavaScript flatten array of objects | Example code

  • by

Use the Array concat() method to flatten the array of objects in JavaScript. ES 2020 gives the flat, also flatMap if you want to iterate over, to flat lists of lists:

[['object1'], ['object2']].flat()

JavaScript flatten an array of objects

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>
    var arr = [['obj1', 'obj2'],
    ['obj11'],
    ['obj12','obj22','obj33']];

    var flattened = [].concat.apply([],arr);

    console.log(flattened);
  </script>

</body>
</html> 

Output:

JavaScript flatten array of objects

Using flat() method

const data = [ [{id:1}, {id:2}], [{id:3}] ];
const result = data.flat();
console.log(result);

// you can specify the depth

const data2 = [ [ [ {id:1} ], {id:2}], [{id:3}] ];
const result2 = data2.flat(2);

console.log(result2);

Output:

[
  {
    "id": 1
  },
  {
    "id": 2
  },
  {
    "id": 3
  }
]
[
  {
    "id": 1
  },
  {
    "id": 2
  },
  {
    "id": 3
  }
]

You can try Array.reduce(), and flatten the numbers’ arrays by concatenating the numbers with the accumulator:

const arr = [{ numbers: [1, 2, 3] }, { numbers: [4, 5] }, { numbers: [6] }];

const result = arr.reduce((r, obj) => r.concat(obj.numbers), []);

console.log(result);

Output: [1, 2, 3, 4, 5, 6]

Do comment if you have any doubts or suggestions on this JS array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.