Skip to content

Commit

Permalink
fix: map export (#467)
Browse files Browse the repository at this point in the history
When exporting a map check for values which are otto.Value and process
them. This is a one level export and no additional traversal is done.

Fixes #252
  • Loading branch information
stevenh committed Nov 28, 2022
1 parent c745096 commit ec2dc5e
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
31 changes: 31 additions & 0 deletions issue_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package otto
import (
"database/sql"
"database/sql/driver"
"encoding/json"
"errors"
"fmt"
"testing"
Expand Down Expand Up @@ -1074,3 +1075,33 @@ func Test_issue317(t *testing.T) {
})
}
}

func Test_issue252(t *testing.T) {
in := map[string]interface{}{
"attr": []interface{}{"string"},
}
expected := map[string]interface{}{
"attr": []string{"changed"},
}

vm := New()
err := vm.Set("In", in)
require.NoError(t, err)

result, err := vm.Run(`(function fn() {
var tmp = In;
tmp.attr = ["changed"];
return tmp;
})()`)
require.NoError(t, err)

actual, err := result.Export()
require.NoError(t, err)
require.Equal(t, expected, actual)

expBs, err := json.Marshal(expected)
require.NoError(t, err)
actBs, err := json.Marshal(actual)
require.NoError(t, err)
require.Equal(t, expBs, actBs)
}
7 changes: 7 additions & 0 deletions value.go
Original file line number Diff line number Diff line change
Expand Up @@ -645,6 +645,13 @@ func (self Value) export() interface{} {
case *_goStructObject:
return value.value.Interface()
case *_goMapObject:
iter := value.value.MapRange()
for iter.Next() {
v := iter.Value()
if ov, ok := v.Interface().(Value); ok {
value.value.SetMapIndex(iter.Key(), reflect.ValueOf(ov.export()))
}
}
return value.value.Interface()
case *_goArrayObject:
return value.value.Interface()
Expand Down

0 comments on commit ec2dc5e

Please sign in to comment.