0

I have the following array of objects that comes from a MySql query:

[
  {col1:1, col2:a},
  {col1:1, col2:b},
  {col1:1, col2:c},
  {col1:2, col2:d},
  {col1:2, col2:e},
  {col1:2, col2:f},
  {col1:3, col2:g},
  {col1:3, col2:h}
]

I would like to transform into the following object:

[
  {col1:1, col2:[a,b,c]},
  {col1:2, col2:[d,e,f]},
  {col1:3, col2:[e,g,h]}
]

Is there a way to perform this task using map or array filter?

IgorAlves
  • 5,086
  • 10
  • 52
  • 83
  • 2
    This is a duplicate, as flagged above, but you could simply query your database to return the grouped result `SELECT col1, JSON_ARRAYAGG(col2) as col2 FROM table GROUP BY col1;` – pilchard Apr 14 '22 at 17:04
  • Demo of above [db-fiddle](https://www.db-fiddle.com/f/uR3yMHDXMCqdT5zwt3qzTb/0) – pilchard Apr 14 '22 at 17:14
  • @pilchard that is better than manipulate in JS. It solved the issue. Tks – IgorAlves Apr 14 '22 at 17:17

0 Answers0