The data shown above is obtained as a read operation returning multiple rows from the db (this can be thought of as the result set for the query we execute)
The data thus obtained needs to be transformed to the below json
[
{
"Industry": "Agriculture",
"SubIndustries": [
{
"IndustryCode": "1",
"SubIndustry": "Dairy"
},
{
"IndustryCode": "2",
"SubIndustry": "Bio"
},
{
"IndustryCode": "3",
"SubIndustry": "Leather"
}
]
},
{
"Industry": "Software",
"SubIndustries": [
{
"IndustryCode": "4",
"SubIndustry": "Services"
},
{
"IndustryCode": "5",
"SubIndustry": "Development"
},
{
"IndustryCode": "6",
"SubIndustry": "Maintenance"
}
]
},
{
"Industry": "Manufacturing",
"SubIndustries": [
{
"IndustryCode": "7",
"SubIndustry": "Tetra Packs"
}
]
}
]
The Algorithm used would be (golang specific)
- Read all data from db in one go
- Create a map[string][]SubIndustryData
- Iterate over all rows, for each row, do step 4
- If the Industry for current row is already present as key in the map from step 2, append SubIndustryData{Code,Description} to slice against existing key
- If the Industry for current row is not present as key in the map from step 2, cretae a slice of type SubIndustryData, append SubIndustryData{IndustryCode,Description} to slice and assign slice to map[Industry]
- Once all data has been seggregated, go through each item in map and append each key,value to build response.
Is there a more efficient way to do this in golang?
