-
Notifications
You must be signed in to change notification settings - Fork 0
/
struct.go
45 lines (36 loc) · 923 Bytes
/
struct.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package utils
import (
"reflect"
"github.com/fatih/structs"
)
func Struct2Map(obj interface{}) map[string]interface{} {
t := reflect.TypeOf(obj)
v := reflect.ValueOf(obj)
var data = make(map[string]interface{})
for i := 0; i < t.NumField(); i++ {
data[t.Field(i).Name] = v.Field(i).Interface()
}
return data
}
func Structs2Maps(list []interface{}) []map[string]interface{} {
ret := make([]map[string]interface{}, 0)
for _, item := range list {
ret = append(ret, structs.Map(item))
}
return ret
}
func Struct2MapOmitEmpty(obj interface{}) map[string]interface{} {
t := reflect.TypeOf(obj).Elem()
v := reflect.ValueOf(obj).Elem()
var data = make(map[string]interface{})
for i := 0; i < t.NumField(); i++ {
if !v.Field(i).IsZero() {
if t.Field(i).Name == "ID" {
data["_id"] = v.Field(i).Interface()
} else {
data[t.Field(i).Name] = v.Field(i).Interface()
}
}
}
return data
}