Closed p8a closed 2 months ago
The property name will be model.Single
, not model.single
, unless you use UncapFieldNameMapper
.
Thanks, UncapFieldNameMapper
fixes both situations (I was using TagFieldNameMapper
).
I have a related question: what is the best, most efficient way to expose a Go map to JS ? If I do it directly forEach
does not work - although it does work for arrays:
Go code:
s.vm.Set("arrayTest", []string{
"one", "two", "three",
})
s.vm.Set("mapTest", map[string][]string{
"one": {"a", "b"},
"two": {"c", "d"},
})
JavaScript code:
arrayTest.forEach((v) => log("array:", v));
mapTest.forEach((v, k, m) => {
log("map:", k);
})
Output:
array: one
array: two
array: three
rules/foreach.js TypeError: Object has no member 'forEach' at rules/foreach.js:8:16(8)
Manually constructing a Map
object in JS using Object.entries
works:
const foo = new Map(Object.entries(mapTest));
foo.forEach((v, k, m) => {
log("js map:", k, v);
})
Output:
js map: one [a b]
js map: two [c d]
Thanks
Please make sure you read the documentation for the ToValue() method. It should answer all your questions.
I did, just wanted to confirm my understanding is correct: to get a "true" Map
(one that has foreach
, etc) I have to initialize it either in JavaScript (my example from the last comment) or in Go - there is no "auto-magic" which wraps Go maps in JavaScript Map
I have an object model defined in Go which I want to pass to JS rules to be verified but I cannot figure out, for example, how to get the string or array length of the Go objects from JS.
This is the Go code:
First attempt was to use JS
length
property which fails (I'm assuming Go strings are not mapped to actual JS strings):results in
Second attempt was to write a Go function which will calculate the length - however that function gets
undefined
as the argument instead of the actual value.Updated Go code:
Updated JS code:
Output:
What is the best way to make the more complex Go structures available to the JavaScript code while still being able to use
length
,forEach
,map
, etc ?I'm assuming manually exporting the Go structure into a similar
goja
model usinggoja
types (string, array) would work but the model is rather large.