Skip to content

Commit

Permalink
Merge pull request #482 from jhernand/add_dig_map_support
Browse files Browse the repository at this point in the history
Add support for digging inside maps
  • Loading branch information
jhernand authored Oct 11, 2021
2 parents d28ad10 + 4b05de6 commit 9ea5dc2
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
11 changes: 11 additions & 0 deletions data/digger.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,8 @@ func (d *Digger) digFieldFromValue(value reflect.Value, field string) interface{
return d.digFieldFromPtr(value, field)
case reflect.Struct:
return d.digFieldFromStruct(value, field)
case reflect.Map:
return d.digFieldFromMap(value, field)
default:
return nil
}
Expand Down Expand Up @@ -173,6 +175,15 @@ func (d *Digger) digFieldFromMethod(value reflect.Value, method reflect.Method)
return result.Interface()
}

func (d *Digger) digFieldFromMap(value reflect.Value, name string) interface{} {
key := reflect.ValueOf(name)
result := value.MapIndex(key)
if !result.IsValid() {
return nil
}
return result.Interface()
}

// lookupMethod tries to find a public method of the given value that matches the given path
// segment. For example, if the path segment is `my_field` it will look for a method named
// `GetMyField` or `MyField`. Only methods that don't have input parameters will be considered.
Expand Down
18 changes: 18 additions & 0 deletions data/digger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,24 @@ var _ = Describe("Digger", func() {
"does_not_exist",
nil,
),
Entry(
"Map field",
map[string]interface{}{
"id": "123",
},
"id",
"123",
),
Entry(
"Nested map field",
map[string]interface{}{
"object": map[string]interface{}{
"id": "123",
},
},
"object.id",
"123",
),
)
})

Expand Down

0 comments on commit 9ea5dc2

Please sign in to comment.