当前位置:网站首页>Golang map数组按字段分类
Golang map数组按字段分类
2022-08-02 11:40:00 【棒洗啦】
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数据如下:
"data": [
{
"id": 1,
"category_id": 6,
"name": "凉拌牛肉",
"price": "45",
"remark": "",
"status": 0
},
{
"id": 2,
"category_id": 7,
"name": "牛肉干饺",
"price": "17",
"remark": "",
"status": 0
},
{
"id": 3,
"category_id": 7,
"name": "牛肉汤饺",
"price": "17",
"remark": "",
"status": 0
},
{
"id": 4,
"category_id": 7,
"name": "酸汤饺子",
"price": "18",
"remark": "",
"status": 0
},
{
"id": 5,
"category_id": 7,
"name": "烩饺",
"price": "19",
"remark": "",
"status": 0
}
],数据处理
需求
需要根据数据中的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数据
"data": {
"6": [
{
"id": 1,
"name": "凉拌牛肉",
"price": "45",
"remark": ""
}
],
"7": [
{
"id": 2,
"name": "牛肉干饺",
"price": "17",
"remark": ""
},
{
"id": 3,
"name": "牛肉汤饺",
"price": "17",
"remark": ""
},
{
"id": 4,
"name": "酸汤饺子",
"price": "18",
"remark": ""
},
{
"id": 5,
"name": "烩饺",
"price": "19",
"remark": ""
}
]
},边栏推荐
猜你喜欢

云原生(三十) | Kubernetes篇之应用商店-Helm介绍

观察者(observer)模式(二) —— 实现线程安全的监听器

LeetCode每日一练 —— 20. 有效的括号

AQS-AbstractQueuedSynchronizer

使用mosquitto过程中的问题解决

使用kubesphere图形界面创建一个应用操作流程

打破千篇一律,DIY属于自己独一无二的商城

npm WARN config global `--global`, `--local` are deprecated. Use `--location解决方案

FinClip | 来了, 2022 年 7 月更新大盘点

sva 断言资料
随机推荐
使用无界队列的线程池会导致内存飙升吗?
Metaverse "Drummer" Unity: Crazy expansion, suspense still exists
喜迎八一 《社会企业开展应聘文职人员培训规范》团体标准出版发行会暨橄榄枝大课堂上线发布会在北京举行
QT笔记——在一个窗口上显示另外一个透明窗口
WPF 实现窗体抖动效果
ASP.NET Core 6框架揭秘实例演示[31]:路由“高阶”用法
阿苹的思考
解决anaconda下载pytorch速度极慢的方法
流动性质押挖矿系统开发如何制作?单双币系统开发成熟技术
MySQL主从复制几个重要的启动选项
【2022 小目标检测综述】Towards Large-Scale Small Object Detection: Survey and Benchmarks
数字化转型中的低代码
[kali-information collection] (1.9) Metasploit + search engine tool Shodan
Oracle 19c 连接PDB
划分训练集,验证集,测试集
Jest 测试框架 beforeEach 的设计原理解析
小程序插件的生态丰富,加速开发建设效率
借小程序容器打造自有App小程序生态
Create your own app applet ecosystem with applet containers
Idea 全局搜索(idea如何全局搜索关键字)