diff --git a/accessors.go b/accessors.go index 1377104..80ad167 100644 --- a/accessors.go +++ b/accessors.go @@ -1,6 +1,7 @@ package objx import ( + "reflect" "regexp" "strconv" "strings" @@ -141,9 +142,10 @@ func access(current interface{}, selector string, value interface{}, isSet bool) default: current = nil } + // do we need to access the item of an array? if index > -1 { - if array, ok := current.([]interface{}); ok { + if array, ok := interSlice(current); ok { if index < len(array) { current = array[index] } else { @@ -156,3 +158,22 @@ func access(current interface{}, selector string, value interface{}, isSet bool) } return current } + +func interSlice(slice interface{}) ([]interface{}, bool) { + if array, ok := slice.([]interface{}); ok { + return array, ok + } + + s := reflect.ValueOf(slice) + if s.Kind() != reflect.Slice { + return nil, false + } + + ret := make([]interface{}, s.Len()) + + for i := 0; i < s.Len(); i++ { + ret[i] = s.Index(i).Interface() + } + + return ret, true +} diff --git a/accessors_test.go b/accessors_test.go index 8bdb69b..a3ee410 100644 --- a/accessors_test.go +++ b/accessors_test.go @@ -24,11 +24,21 @@ func TestAccessorsAccessGetDeep(t *testing.T) { "name": objx.Map{ "first": "Tyler", "last": "Bunnell", + "friends": []string{ + "Capitol", + "Bollocks", + }, + "ifriends": []interface{}{ + "Capitol", + "Bollocks", + }, }, } assert.Equal(t, "Tyler", m.Get("name.first").Data()) assert.Equal(t, "Bunnell", m.Get("name.last").Data()) + assert.Equal(t, "Capitol", m.Get("name.friends[0]").Data()) + assert.Equal(t, "Capitol", m.Get("name.ifriends[0]").Data()) } func TestAccessorsAccessGetDeepDeep(t *testing.T) {