Skip to content

Add map key matcher #9

@andig

Description

@andig

It seems neither mergo nor mapstructure currently provide this ability. Made a small addition to allow arbitrarily matching map keys:

func merge(dst, src map[string]any, depth int) map[string]any {
	if depth > mergeMaxDepth {
		panic("too deep!")
	}
	for key, srcVal := range src {
		for k := range dst {
			if matchKey(k, key) {
				// overwrite key
				key = k

				srcMap, srcMapOk := mapify(srcVal)
				dstMap, dstMapOk := mapify(dst[k])
				if srcMapOk && dstMapOk {
					srcVal = merge(dstMap, srcMap, depth+1)
				}
				break
			}
		}
		dst[key] = srcVal
	}
	return dst
}

Default

var matchKey = func(a, b string) bool {
	return strings.Compare(a, b) == 0
}

but also

var matchKey = strings.EqualFold

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions