当前位置:网站首页>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": ""
}
]
},
边栏推荐
猜你喜欢
jacoco的学习以及理解
字母交换--字符串dp
基于threejs的商品VR展示平台的设计与实现思路
Mysql transaction isolation level and MVCC (multi-version concurrency control)
Create a devops CI/CD process using the kubesphere GUI
Mysql事务隔离级别与MVCC(多版本并发控制)
OSI 七层模型和TCP/IP模型及对应协议(详解)
C#/VB.NET to add more lines more columns image watermark into the Word document
What is the future of smartwatches?
Create an application operation process using the kubesphere GUI
随机推荐
【MySQL系列】- LIKE查询 以%开头一定会让索引失效吗
STM32+MPU6050 Design Portable Mini Desktop Clock (Automatically Adjust Time Display Direction)
学习经验分享之七:YOLOv5代码中文注释
观察者(observer)模式(二) —— 实现线程安全的监听器
OLED的HAL库代码介绍及使用(stm32f1/I2C/HAL库版/100%一次点亮)
SQL 经典50题(题目+解答)(1)
打破千篇一律,DIY属于自己独一无二的商城
MP的几种查询方式
基于深度学习的裂缝检测技术
翁恺C语言程序设计网课笔记合集
find查找多类型结尾文件
5G网络切片技术
Oracle 19c配置ob server
JSP中如何正确的填写include指令中的file路径呢?
借小程序容器打造自有App小程序生态
【MySQL】多表联合查询、连接查询、子查询「建议收藏」
The sitcom "Re-Walking the Long March" was staged
go源码之sync.Waitgroup
智能手表前景如何?
受邀出席Rust开发者大会|Rust如何助力量化高频交易?