Skip to content

Instantly share code, notes, and snippets.

@niski84
Created November 16, 2018 01:46
Show Gist options
  • Save niski84/a6a3b825b6704cc2cbfd39c97b89e640 to your computer and use it in GitHub Desktop.
Save niski84/a6a3b825b6704cc2cbfd39c97b89e640 to your computer and use it in GitHub Desktop.
golang: Find key in interface (recursively) and return value as interface
// Find key in interface (recursively) and return value as interface
func Find(obj interface{}, key string) (interface{}, bool) {
//if the argument is not a map, ignore it
mobj, ok := obj.(map[string]interface{})
if !ok {
return nil, false
}
for k, v := range mobj {
// key match, return value
if k == key {
return v, true
}
// if the value is a map, search recursively
if m, ok := v.(map[string]interface{}); ok {
if res, ok := Find(m, key); ok {
return res, true
}
}
// if the value is an array, search recursively
// from each element
if va, ok := v.([]interface{}); ok {
for _, a := range va {
if res, ok := Find(a, key); ok {
return res,true
}
}
}
}
// element not found
return nil,false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment