From 7e16e799e440ca5caee8d3ddda7c4e7e0bf2b44a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20Schw=C3=B6rer?= Date: Tue, 23 Jan 2024 17:51:52 +0100 Subject: [PATCH] v0.0.381 --- goextVersion.go | 4 +-- reflectext/convertToMap.go | 72 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+), 2 deletions(-) create mode 100644 reflectext/convertToMap.go diff --git a/goextVersion.go b/goextVersion.go index 0378768..817c11d 100644 --- a/goextVersion.go +++ b/goextVersion.go @@ -1,5 +1,5 @@ package goext -const GoextVersion = "0.0.380" +const GoextVersion = "0.0.381" -const GoextVersionTimestamp = "2024-01-22T12:33:41+0100" +const GoextVersionTimestamp = "2024-01-23T17:51:52+0100" diff --git a/reflectext/convertToMap.go b/reflectext/convertToMap.go new file mode 100644 index 0000000..f8721b4 --- /dev/null +++ b/reflectext/convertToMap.go @@ -0,0 +1,72 @@ +package reflectext + +import "reflect" + +func ConvertStructToMap(v any) any { + return reflectToMap(reflect.ValueOf(v)) +} + +func reflectToMap(fv reflect.Value) any { + + if fv.Kind() == reflect.Ptr { + + if fv.IsNil() { + return nil + } else { + return reflectToMap(fv.Elem()) + } + + } + + if fv.Kind() == reflect.Func { + + // skip + return nil + + } + + if fv.Kind() == reflect.Array { + + arrlen := fv.Len() + arr := make([]any, arrlen) + for i := 0; i < arrlen; i++ { + arr[i] = reflectToMap(fv.Index(i)) + } + return arr + + } + + if fv.Kind() == reflect.Slice { + + arrlen := fv.Len() + arr := make([]any, arrlen) + for i := 0; i < arrlen; i++ { + arr[i] = reflectToMap(fv.Index(i)) + } + return arr + + } + + if fv.Kind() == reflect.Chan { + + // skip + return nil + + } + + if fv.Kind() == reflect.Struct { + + res := make(map[string]any) + + for i := 0; i < fv.NumField(); i++ { + if fv.Type().Field(i).IsExported() { + res[fv.Type().Field(i).Name] = reflectToMap(fv.Field(i)) + } + } + + return res + + } + + return fv.Interface() +}