diff --git a/type_go_struct.go b/type_go_struct.go index 12fa727..e22713c 100644 --- a/type_go_struct.go +++ b/type_go_struct.go @@ -36,8 +36,8 @@ func _newGoStructObject(value reflect.Value) *_goStructObject { } func (self _goStructObject) getValue(name string) reflect.Value { - if f, ok := self.field(name); ok { - return reflect.Indirect(self.value).FieldByIndex(f.Index) + if idx := fieldIndexByName(reflect.Indirect(self.value).Type(), name); len(idx) > 0 { + return reflect.Indirect(self.value).FieldByIndex(idx) } if validGoStructName(name) { @@ -54,14 +54,8 @@ func (self _goStructObject) getValue(name string) reflect.Value { return reflect.Value{} } -func (self _goStructObject) field(name string) (reflect.StructField, bool) { - t := reflect.Indirect(self.value).Type() - - if idx := fieldIndexByName(t, name); len(idx) > 0 { - return t.FieldByIndex(idx), true - } - - return reflect.StructField{}, false +func (self _goStructObject) fieldIndex(name string) []int { + return fieldIndexByName(reflect.Indirect(self.value).Type(), name) } func (self _goStructObject) method(name string) (reflect.Method, bool) { @@ -69,7 +63,7 @@ func (self _goStructObject) method(name string) (reflect.Method, bool) { } func (self _goStructObject) setValue(rt *_runtime, name string, value Value) bool { - if _, exists := self.field(name); !exists { + if idx := fieldIndexByName(reflect.Indirect(self.value).Type(), name); len(idx) == 0 { return false } diff --git a/type_go_struct_test.go b/type_go_struct_test.go new file mode 100644 index 0000000..58d8fa1 --- /dev/null +++ b/type_go_struct_test.go @@ -0,0 +1,33 @@ +package otto + +import ( + "testing" +) + +func TestGoStructEmbeddedFields(t *testing.T) { + type A struct { + A1 string `json:"a1"` + A2 string `json:"a2"` + A3 string `json:"a3"` + } + + type B struct { + A + B1 string `json:"b1"` + } + + tt(t, func() { + test, vm := test() + + var b B + + b.A1 = "a1" + b.A2 = "a2" + b.A3 = "a3" + b.B1 = "b1" + + vm.Set("v", B{A{"a1", "a2", "a3"}, "b1"}) + + test(`[v.a1,v.a2,v.a3,v.b1]`, "a1,a2,a3,b1") + }) +}