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

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?

1 Like

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

1 Like

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


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 Accessing Properties of Untyped JS Values - The `wasm-bindgen` Guide for more.

5 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.