I have the following MySQL tables:
| category | icon |
-------------------
| CAT_A | xxx |
| CAT_B | yyy |
And
| sub_category | icon | category
--------------------------------
| SUB_X | ppp | CAT_A
| SUB_Y | qqq | CAT_A
| SUB_Z | rrr | CAT_B
| SUB_U | www | CAT_B
Now I want to get all the data in a single query I am using Node.JS and I wrote the following query
SELECT c.category categoryTitle, c.icon categoryIcon, s.sub_category subCategoryTitle, s.icon subCategoryIcon FROM categories c INNER JOIN sub_categories s ON c.title = s.category
This is my Node.JS code
var arrCategories = [];
for (var category in rows) {
if (rows.hasOwnProperty(category))
arrCategories.push(rows[category]);
}
response.json(arrCategories);
Now I get the following response
[
{
"categoryTitle":"CAT_A",
"categoryIcon":"xxx",
"subCategoryTitle":"SUB_X",
"subCategoryIcon":"ppp"
},
{
"categoryTitle":"CAT_A",
"categoryIcon":"xxx",
"subCategoryTitle":"SUB_Y",
"subCategoryIcon":"qqq"
},......
]
But I want the following output:
[
{
"categoryTitle":"CAT_A",
"categoryIcon":"xxx",
"subCategory":[
{
"subCategoryTitle":"SUB_X",
"subCategoryIcon":"ppp"
},
{
"subCategoryTitle":"SUB_Y",
"subCategoryIcon":"qqq"
},
]
},......
]
What should I do in order to get the output in the desired format
Any help is appriciated