Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions issue255_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package mergo_test

import (
"testing"

"dario.cat/mergo"
)

type issue255Person struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name,omitempty"`
Password string `json:"-"`
Age int
}

func TestIssue255MapStructToMapWithTaggedKeys(t *testing.T) {
person := issue255Person{
FirstName: "Ada",
LastName: "Lovelace",
Password: "secret",
Age: 36,
}

actual := map[string]interface{}{}
if err := mergo.Map(&actual, person, mergo.WithMapKeyTag("json")); err != nil {
t.Fatal(err)
}

if actual["first_name"] != "Ada" {
t.Fatalf("expected first_name key to be mapped from tag, got %#v", actual)
}
if actual["last_name"] != "Lovelace" {
t.Fatalf("expected tag name to be used, got %#v", actual)
}
if actual["password"] != "secret" {
t.Fatalf("expected '-' tag to fall back to default field name, got %#v", actual)
}
if actual["age"] != 36 {
t.Fatalf("expected untagged field to fall back to default field name, got %#v", actual)
}
}
9 changes: 9 additions & 0 deletions map.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ package mergo
import (
"fmt"
"reflect"
"strings"
"unicode"
"unicode/utf8"
)
Expand Down Expand Up @@ -58,6 +59,14 @@ func deepMap(dst, src reflect.Value, visited map[uintptr]*visit, depth int, conf
}
fieldName := field.Name
fieldName = changeInitialCase(fieldName, unicode.ToLower)
if config.mapKeyTag != "" {
if taggedName := field.Tag.Get(config.mapKeyTag); taggedName != "" {
taggedName, _, _ = strings.Cut(taggedName, ",")
if taggedName != "" && taggedName != "-" {
fieldName = taggedName
}
}
}
if _, ok := dstMap[fieldName]; !ok || (!isEmptyValue(reflect.ValueOf(src.Field(i).Interface()), !config.ShouldNotDereference) && overwrite) || config.overwriteWithEmptyValue {
dstMap[fieldName] = src.Field(i).Interface()
}
Expand Down
8 changes: 8 additions & 0 deletions merge.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ type Config struct {
overwriteWithEmptyValue bool
overwriteSliceWithEmptyValue bool
sliceDeepCopy bool
mapKeyTag string
}

type Transformers interface {
Expand Down Expand Up @@ -367,6 +368,13 @@ func WithSliceDeepCopy(config *Config) {
config.Overwrite = true
}

// WithMapKeyTag uses the named struct tag value as the destination map key when mapping a struct to map.
func WithMapKeyTag(tag string) func(*Config) {
return func(config *Config) {
config.mapKeyTag = tag
}
}

func merge(dst, src interface{}, opts ...func(*Config)) error {
if dst != nil && reflect.ValueOf(dst).Kind() != reflect.Ptr {
return ErrNonPointerArgument
Expand Down