Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes #88 #95

Merged
merged 3 commits into from
Apr 15, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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