Go-like two-dimensional arrays are classified by fields/map arrays are classified by fields
Raw data
data corresponding structure
type IgmsMenu struct {
ID uint `gorm:"column:id;" json:"id"`
CategoryId int64 `gorm:"column:category_id;" json:"category_id"`
Name string `gorm:"column:name;" json:"name"`
Price *decimal.Decimal `gorm:"column:price;type:decimal" json:"price"`
Remark string `gorm:"column:remark;" json:"remark"`
Status int8 `gorm:"column:status;default:0;" json:"status"`
}
The json data returned by the original data is as follows:
data processing
need
The array classification needs to be done according to the category_id in the data .
principle
Since the data type of category_id is int64 , it is necessary to define a type of map[int64][]map[string]interface{} to accept the processed data.
- map[int64]: This layer is used to undertake various types of array sets after classification
- []map[string]interface{}: data array of a single class
the code
func LauwenDeal(infos []model.IgmsMenu) map[int64][]map[string]interface{} {
res := make(map[int64][]map[string]interface{})
for _, item := range infos {
temp := map[string]interface{}{
"id": item.ID,
"name": item.Name,
"price": item.Price,
"remark": item.Remark,
}
res[0] = append(res[0], temp)
res[item.CategoryId] = append(res[item.CategoryId], temp)
}
return res
}
process result
The json data returned after processing