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
| func ArrayStructToMap(val interface{}, key string) (res map[string]interface{}, err error) {
v := reflect.ValueOf(val)
if v.Kind() != reflect.Slice {
return nil, fmt.Errorf("argument must be a slice")
}
res = make(map[string]interface{})
for i := 0; i < v.Len(); i++ {
vIndex := v.Index(i)
vType := vIndex.Type()
st := vIndex.Convert(vType)
// 获取列名为 key 的 value
keyValue := st.FieldByName(key)
if keyValue.IsValid() {
var _key = strconv.FormatUint(keyValue.Uint(), 10)
res[_key] = vIndex.Interface()
} else {
return nil, fmt.Errorf("未找到列名数据: %s", key)
}
}
return res, nil
}
|