Skip to content

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 flattens 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]

Or you can use a combination of Array.prototype.map() and Array.prototype.reduce() methods.

const arr = [
  { id: 1, name: 'John', age: 30 },
  { id: 2, name: 'Jane', age: 25 },
  { id: 3, name: 'Bob', age: 40 }
];

const flattened = arr.map(obj => {
  return Object.values(obj);
}).reduce((a, b) => {
  return a.concat(b);
});

console.log(flattened); // [1, "John", 30, 2, "Jane", 25, 3, "Bob", 40]

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading