Files
appcore/structs/structs.go

45 lines
907 B
Go
Raw Normal View History

2025-06-16 22:19:00 +05:30
// Copyright 2024 Patial Tech (Ankit Patial).
2025-06-16 22:26:47 +05:30
//
// This file is part of code.patial.tech/go/appcore, which is MIT licensed.
// See http://opensource.org/licenses/MIT
2025-06-16 22:19:00 +05:30
package structs
import (
"reflect"
)
func Map(obj any) map[string]any {
result := make(map[string]any)
val := reflect.ValueOf(obj)
if val.Kind() == reflect.Pointer {
2025-06-16 22:19:00 +05:30
val = val.Elem()
}
typ := val.Type()
for i := range val.NumField() {
fieldName := typ.Field(i).Name
2026-02-20 16:38:24 +05:30
field := val.Field(i)
fieldValueKind := field.Kind()
2025-06-16 22:19:00 +05:30
var fieldValue any
2026-02-20 16:38:24 +05:30
switch fieldValueKind {
case reflect.Struct:
fieldValue = Map(field.Interface())
case reflect.Pointer:
if !field.IsNil() && field.Elem().Kind() == reflect.Struct {
fieldValue = Map(field.Elem().Interface())
} else {
fieldValue = field.Interface()
}
default:
fieldValue = field.Interface()
2025-06-16 22:19:00 +05:30
}
result[fieldName] = fieldValue
}
return result
}