Skip to content

Commit 35313a9

Browse files
geseqhanzei
authored andcommitted
Fixes #88 (#95)
1 parent a4ea3d6 commit 35313a9

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

accessors.go

+22-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package objx
22

33
import (
4+
"reflect"
45
"regexp"
56
"strconv"
67
"strings"
@@ -141,9 +142,10 @@ func access(current interface{}, selector string, value interface{}, isSet bool)
141142
default:
142143
current = nil
143144
}
145+
144146
// do we need to access the item of an array?
145147
if index > -1 {
146-
if array, ok := current.([]interface{}); ok {
148+
if array, ok := interSlice(current); ok {
147149
if index < len(array) {
148150
current = array[index]
149151
} else {
@@ -156,3 +158,22 @@ func access(current interface{}, selector string, value interface{}, isSet bool)
156158
}
157159
return current
158160
}
161+
162+
func interSlice(slice interface{}) ([]interface{}, bool) {
163+
if array, ok := slice.([]interface{}); ok {
164+
return array, ok
165+
}
166+
167+
s := reflect.ValueOf(slice)
168+
if s.Kind() != reflect.Slice {
169+
return nil, false
170+
}
171+
172+
ret := make([]interface{}, s.Len())
173+
174+
for i := 0; i < s.Len(); i++ {
175+
ret[i] = s.Index(i).Interface()
176+
}
177+
178+
return ret, true
179+
}

accessors_test.go

+10
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,21 @@ func TestAccessorsAccessGetDeep(t *testing.T) {
2424
"name": objx.Map{
2525
"first": "Tyler",
2626
"last": "Bunnell",
27+
"friends": []string{
28+
"Capitol",
29+
"Bollocks",
30+
},
31+
"ifriends": []interface{}{
32+
"Capitol",
33+
"Bollocks",
34+
},
2735
},
2836
}
2937

3038
assert.Equal(t, "Tyler", m.Get("name.first").Data())
3139
assert.Equal(t, "Bunnell", m.Get("name.last").Data())
40+
assert.Equal(t, "Capitol", m.Get("name.friends[0]").Data())
41+
assert.Equal(t, "Capitol", m.Get("name.ifriends[0]").Data())
3242
}
3343

3444
func TestAccessorsAccessGetDeepDeep(t *testing.T) {

0 commit comments

Comments
 (0)