Accessing Properties of Untyped JavaScript Values

To read and write arbitrary properties from any untyped JavaScript value regardless if it is an instanceof some JavaScript class or not, use the js_sys::Reflect APIs. These APIs are bindings to the JavaScript builtin Reflect object and its methods.

You might also benefit from using duck-typed interfaces instead of working with untyped values.

Reading Properties with js_sys::Reflect::get

API documentation for js_sys::Reflect::get.

A function that returns the value of a property.

Rust Usage

#![allow(unused)]
fn main() {
let value = js_sys::Reflect::get(&target, &property_key)?;
}

JavaScript Equivalent

let value = target[property_key];

Writing Properties with js_sys::Reflect::set

API documentation for js_sys::Reflect::set.

A function that assigns a value to a property. Returns a boolean that is true if the update was successful.

Rust Usage

#![allow(unused)]
fn main() {
js_sys::Reflect::set(&target, &property_key, &value)?;
}

JavaScript Equivalent

target[property_key] = value;

Determining if a Property Exists with js_sys::Reflect::has

API documentation for js_sys::Reflect::has.

The JavaScript in operator as function. Returns a boolean indicating whether an own or inherited property exists on the target.

Rust Usage

#![allow(unused)]
fn main() {
if js_sys::Reflect::has(&target, &property_key)? {
    // ...
} else {
    // ...
}
}

JavaScript Equivalent

if (property_key in target) {
    // ...
} else {
    // ...
}

But wait — there's more!

See the js_sys::Reflect API documentation for the full listing of JavaScript value reflection and introspection capabilities.