Skip to content

Commit

Permalink
Fixes stretchr#88
Browse files Browse the repository at this point in the history
  • Loading branch information
geseq committed Apr 15, 2019
1 parent a4ea3d6 commit 06b504d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
24 changes: 23 additions & 1 deletion accessors.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package objx

import (
"reflect"
"regexp"
"strconv"
"strings"
Expand Down Expand Up @@ -141,9 +142,15 @@ 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 {
array, ok := current.([]interface{})
if !ok {
array, ok = interSlice(current)
}

if ok {
if index < len(array) {
current = array[index]
} else {
Expand All @@ -156,3 +163,18 @@ func access(current interface{}, selector string, value interface{}, isSet bool)
}
return current
}

func interSlice(slice interface{}) ([]interface{}, bool) {
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
}
5 changes: 5 additions & 0 deletions accessors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,16 @@ func TestAccessorsAccessGetDeep(t *testing.T) {
"name": objx.Map{
"first": "Tyler",
"last": "Bunnell",
"friends": []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())
}

func TestAccessorsAccessGetDeepDeep(t *testing.T) {
Expand Down

0 comments on commit 06b504d

Please sign in to comment.