Last active
June 11, 2021 07:27
-
-
Save Spazzy757/ed29c3fa3b870c7d7d6085a03435d868 to your computer and use it in GitHub Desktop.
Takes two map[string]interface{} types and recursively merges them. The second object will take precedence in case of clashes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//mergeObjects will take two interfaces | |
//and add them together | |
//NOTE: if keys clash, object two will overwite | |
//object ones key | |
func mergeObjects( | |
objectOne map[string]interface{}, | |
objectTwo map[string]interface{}, | |
) map[string]interface{} { | |
data := make(map[string]interface{}) | |
// loop through first object adding | |
// keys to data | |
for k, v := range objectOne { | |
if _, ok := objectOne[k]; ok { | |
data[k] = v | |
} | |
} | |
// loop through object two | |
for k1, v1 := range objectTwo { | |
// if key exists in object two | |
if _, ok := objectTwo[k1]; ok { | |
// check if object two key exists | |
// in data if not just set it in data | |
if _, ok := data[k1]; !ok { | |
data[k1] = v1 | |
continue | |
} | |
// loop through data | |
for k2, _ := range data { | |
// if data has the same key as object two | |
if k1 == k2 { | |
// check if both are of type map[string]interface{} | |
// if yes then recursion | |
interfaceType := fmt.Sprintf("%T", map[string]interface{}{}) | |
if fmt.Sprintf("%T", data[k2]) == interfaceType && | |
fmt.Sprintf("%T", objectTwo[k1]) == interfaceType { | |
data[k2] = mergeObjects( | |
data[k2].(map[string]interface{}), | |
objectTwo[k1].(map[string]interface{}), | |
) | |
} else { | |
// if not object two will take precedence | |
// so set data to objectTwo value | |
data[k2] = v1 | |
} | |
} | |
} | |
} | |
} | |
return data | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment