Go 类二维数组按字段分类/map数组按字段分类
原始数据
数据相应结构体
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"`
}
原始数据返回的json数据如下:
数据处理
需求
需要根据数据中的category_id来做数组分类。
原理
因category_id的数据类型为int64,所以需要定义一个类型为map[int64][]map[string]interface{}的来承接处理后的数据。
- map[int64]:这层用来承接分类后的各类数组集
- []map[string]interface{}:单个类的数据数组
代码
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
}
处理结果
处理后返回的json数据