Skip to content

Commit

Permalink
Fixes #88 (#95)
Browse files Browse the repository at this point in the history
  • Loading branch information
geseq authored and hanzei committed Apr 15, 2019
1 parent a4ea3d6 commit 35313a9
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
23 changes: 22 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,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 {
Expand All @@ -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
}
10 changes: 10 additions & 0 deletions accessors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit 35313a9

Please sign in to comment.