当前位置:网站首页>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": ""
}
]
},
边栏推荐
- 小程序插件让开发者受益的几个理由
- go源码之sync.Waitgroup
- Getting Started with Three.JS Programmatic Modeling
- SQL function TRIM
- Excel dynamic chart production
- npm WARN deprecated [email protected] This version of tar is no longer supported, and will not receive
- Excel动态图制作
- ansible module --yum module
- STM32+MPU6050 Design Portable Mini Desktop Clock (Automatically Adjust Time Display Direction)
- Metaverse "Drummer" Unity: Crazy expansion, suspense still exists
猜你喜欢
随机推荐
Running yum reports Error: Cannot retrieve metalink for reposit
yolo格式(txt)数据集转VOC(xml)
多线程之生产者与消费者
MP的几种查询方式
SQL function TRIM
Excel dynamic chart production
放苹果(暑假每日一题 13)
Create a devops CI/CD process using the kubesphere GUI
受邀出席Rust开发者大会|Rust如何助力量化高频交易?
如何通过DBeaver 连接 TDengine?
CAN总线的AUTOSAR网络管理
华为eNSP(基础实验通信)
pyqt5连接MYSQL数据库问题
【kali-信息收集】(1.9)Metasploit+搜索引擎工具Shodan
STM32+MPU6050 Design Portable Mini Desktop Clock (Automatically Adjust Time Display Direction)
SQL function $TRANSLATE
ssm网页访问数据库数据报错
云原生(三十) | Kubernetes篇之应用商店-Helm介绍
idea常用插件
OSI 七层模型和TCP/IP模型及对应协议(详解)