- 重新实现utils.Struct2FlatMap

This commit is contained in:
gazebo
2019-09-24 15:23:27 +08:00
parent 3ae979e48b
commit b02230ec2d
3 changed files with 42 additions and 37 deletions

View File

@@ -13,7 +13,7 @@ import (
"time"
"git.rosy.net.cn/baseapi"
"github.com/fatih/structs"
"github.com/gazeboxu/structs"
"github.com/mitchellh/mapstructure"
)
@@ -449,43 +449,22 @@ func MergeMaps(firstMap map[string]interface{}, otherMaps ...map[string]interfac
return retVal
}
func Struct2Map(obj interface{}, tagName string) (mapData map[string]interface{}) {
func Struct2Map(obj interface{}, tagName string, isFlattenAnonymous bool) (mapData map[string]interface{}) {
if tagName == "" {
tagName = "json"
}
structsObj := structs.New(obj)
structsObj.TagName = tagName
structsObj.IsFlattenAnonymous = true
return structsObj.Map()
}
func Struct2MapByJson(obj interface{}) (mapData map[string]interface{}) {
return Struct2Map(obj, "")
}
// 此函数将MAP中所有的子MAP中的数据提升到最上层相同字段会覆盖父MAP的
func FlatMap(in map[string]interface{}) map[string]interface{} {
keys := []string{}
maps := []map[string]interface{}{}
for k, v := range in {
if vMap, ok := v.(map[string]interface{}); ok {
vMap = FlatMap(vMap)
maps = append(maps, vMap)
keys = append(keys, k)
}
}
if len(maps) > 0 {
retVal := MergeMaps(in, maps...)
for _, v := range keys {
delete(retVal, v)
}
return retVal
}
return in
return Struct2Map(obj, "", false)
}
func Struct2FlatMap(obj interface{}) map[string]interface{} {
m := Struct2MapByJson(obj)
return FlatMap(m)
return Struct2Map(obj, "", true)
}
// !!! 此函数好像不支持struct是内嵌结构的