dop251 / goja

ECMAScript/JavaScript engine in pure Go
MIT License
5.63k stars 378 forks source link

Export JS array to Go slice #573

Closed jimafisk closed 5 months ago

jimafisk commented 6 months ago

Goja is an awesome project, thank you for the tremendous work you've put into it!

I was hoping get an array of values from a JS script and iterate over them in Go, but I'm not sure exactly how to do that. I was trying (unsuccessfully) something along these lines:

vm := goja.New()       
r, _ := vm.RunString(`["cat", "dog", "whale"]`)
v, _ := r.Export().([]string)
for i, a := range v {
  fmt.Println("index:", i)
  fmt.Println("animal:", a)
}

In following along on a similar issue, it seems like exportToSlice might be exactly what I'm looking for. I don't see this in the documentation, is this currently available or still a work in progress?

I also tried using .ForOf which has a great example in the docs (https://pkg.go.dev/github.com/dop251/goja#Runtime.ForOf), but I still only seem to be able to get it to iterate character by character over the array as a string.

I would love to see an example of how to export a JS array to a Go slice if it's something you could point me to or demonstrate without too much difficulty. Thank you!

dop251 commented 5 months ago

You should use ExportTo

jimafisk commented 5 months ago

Thank you @dop251, that was exactly what I needed! This example was super helpful for me: https://pkg.go.dev/github.com/dop251/goja#example-Runtime.ExportTo-ArrayLikeToSlice

Updating my initial example:

vm := goja.New()

v, err := vm.RunString(`["cat", "dog", "whale"]`)
if err != nil {
   log.Fatal(err)
}

var r []string

err = vm.ExportTo(v, &r)
if err != nil {
   log.Fatal(err)
}

for i, a := range r {
   fmt.Println("index: ", i)
   fmt.Println("animal: ", a)
}