Reputation: 348
Is there a better way than iter to convert HashMap
to JsValue
?
let mut map = HashMap::new<String, String>();
// put stuff in the map...
let obj = js_sys::Object::new();
for (k,v) in map.iter() {
let key = JsValue::from(k);
let value = JsValue::from(v);
js_sys::Reflect::set(&obj, &key, &value).unwrap();
}
JsValue::from(obj)
Upvotes: 1
Views: 1369
Reputation: 60167
From Serializing and Deserializing Arbitrary Data Into and From JsValue
with Serde in the wasm-bindgen guide: you can convert any type that is Serialize
-able with the help of the serde-wasm-bindgen crate:
Using it, your code would look like this:
serde_wasm_bindgen::to_value(&map).unwrap()
The guide lists another crate, gloo-utils, that offers similar functionality but communicates data differently over the Wasm/Javascript bridge.
Upvotes: 1