How to convert multiple rows into an array within another?

Viewed 20

I performed a SQL query which resulted in a JavaScript Object like so:

[
  {
    category_name: 'Example',
    category_id: 1,
    subcategory_name: 'Example Subcategory 1',
    subcategory_id: 1
  },
  {
    category_name: 'Example',
    category_id: 1,
    subcategory_name: 'Example Subcategory 2',
    subcategory_id: 2
  },
  {
    category_name: 'Example 2',
    category_id: 2,
    subcategory_name: 'Example Subcategory 3',
    subcategory_id: 3
  }
]

and I would like to convert it into such a format:

[
  {
     category_name: 'Example',
     category_id: 1,
     subcategories: [
        {
           id: 1,
           name: 'Example Subcategory 1'
        },
        {
           id: 2,
           name: 'Example Subcategory 2'
        }
     ]
   }
(and so on)
]

How would I go about doing this, either in SQL query itself or in JavaScript.

The SQL query I used is:

SELECT 
    C.category_id,
    C.name AS category_name,
    S.subcategory_id,
    S.name AS subcategory_name
FROM
    categories C
        INNER JOIN
    subcategories S ON S.category_id = C.category_id
WHERE
    C.deleted = 0 AND S.deleted = 0
0 Answers
Related