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

 

数据处理

需求

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

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值