[wasm_bindgen] How do I manually create and manipulate a JS object?

#1

The wasm-bindgen crate has an API to create JsValue values, which is documented here. There’s the obvious stuff like creating strings, booleans, null and undefined, but what I’m missing is a way to manually initialize and manipulate a JavaScript Object.

I’m aware of the crate’s suggestion to use serde but the way that that serializes my data is not the shape that is expected on the other side. Therefore, I need to be able to create and manipulate Javascript objects manually.
And while I’ve found the API for Object, it is not clear at all how to convert that into a JsValue if I were to create one.

Does anyone have a clear idea of how to manually create and manipulate JS objects from rust using the wasm-bindgen API?

0 Likes

#2

Reflect is the alternative javascript way. Then there is eval.
(Expect there is something more but not farmiliar enough with wasm-bindgen.)

0 Likes

#3

js_sys::Object derefs to wasm_bindgen::JsValue (and also Into)

https://docs.rs/js-sys/0.3.17/js_sys/struct.Object.html#deref-methods


You should be able to do something like this (untested):

// Roughly equivalent to `let obj = new Object; obj.foo = "bar";`
let obj = js_sys::Object::new();
js_sys::Reflect::set(&obj, &"foo".into(), &"bar".into());

See https://rustwasm.github.io/docs/wasm-bindgen/reference/accessing-properties-of-untyped-js-values.html for more.

3 Likes