Golang map数组按字段分类

简介: Golang map数组按字段分类

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数据如下:

15050284c8e04be582eafcd6510a3bb1.png

数据处理


需求


需要根据数据中的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数据

0d30c2bd32804afe898480c860bf34a1.png

目录
相关文章
|
6天前
|
Go
golang力扣leetcode 238.除自身以外数组的乘积
golang力扣leetcode 238.除自身以外数组的乘积
19 0
|
6天前
|
Go
golang力扣leetcode 152.乘积最大子数组
golang力扣leetcode 152.乘积最大子数组
34 0
|
6天前
|
Go
golang力扣leetcode 75.颜色分类
golang力扣leetcode 75.颜色分类
27 0
|
6天前
|
Go
golang力扣leetcode 954.二倍数对数组
golang力扣leetcode 954.二倍数对数组
18 0
|
6天前
|
Go
golang力扣leetcode 34.在排序数组中查找元素的第一个和最后一个位置
golang力扣leetcode 34.在排序数组中查找元素的第一个和最后一个位置
71 0
|
6天前
|
Go
golang力扣leetcode 462.最少移动次数使数组元素相等II
golang力扣leetcode 462.最少移动次数使数组元素相等II
37 0
|
6天前
|
存储 编译器 Go
Golang深入浅出之-掌握Go语言Map:初始化、增删查改与遍历
【4月更文挑战第21天】Go语言中的`map`提供快速的键值对操作,包括初始化、增删查改和遍历。初始化时,推荐使用`make()`函数,如`make(map[string]int)`。插入和查询键值对直接通过索引访问,更新则重新赋值。删除键值对需用`delete()`函数,确保键存在。遍历map常用`for range`,注意避免在遍历中修改map。了解这些并避免易错点,能提升代码效率和可读性。
22 1
Golang深入浅出之-掌握Go语言Map:初始化、增删查改与遍历
|
6天前
|
Go 数据安全/隐私保护
第九章 Golang中map
第九章 Golang中map
25 2
|
6天前
|
Go
【Golang】使用泛型对数组进行去重
【2月更文挑战第11天】使用泛型对数组进行去重
32 0
|
6天前
|
Java Go C++
Golang每日一练(leetDay0114) 矩阵中的最长递增路径、按要求补齐数组
Golang每日一练(leetDay0114) 矩阵中的最长递增路径、按要求补齐数组
36 0
Golang每日一练(leetDay0114) 矩阵中的最长递增路径、按要求补齐数组