diff --git a/core/engine/src/object/operations.rs b/core/engine/src/object/operations.rs index a607f70fe0..6cee0140e1 100644 --- a/core/engine/src/object/operations.rs +++ b/core/engine/src/object/operations.rs @@ -343,6 +343,16 @@ impl JsObject { Ok(desc.is_some()) } + /// Get all the keys of the properties of this object. + /// + /// More information: + /// - [ECMAScript reference][spec] + /// + /// [spec]: https://tc39.es/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-ownpropertykeys + pub fn own_property_keys(&self, context: &mut Context) -> JsResult> { + self.__own_property_keys__(context) + } + /// `Call ( F, V [ , argumentsList ] )` /// /// # Panics diff --git a/examples/src/bin/properties.rs b/examples/src/bin/properties.rs new file mode 100644 index 0000000000..ab92e7789a --- /dev/null +++ b/examples/src/bin/properties.rs @@ -0,0 +1,31 @@ +// This example shows how to access the keys and values of a `JsObject` + +use boa_engine::{ + js_string, property::PropertyKey, Context, JsError, JsNativeError, JsValue, Source, +}; + +fn main() -> Result<(), JsError> { + // We create a new `Context` to create a new Javascript executor. + let mut context = Context::default(); + + let value = context.eval(Source::from_bytes("({ x: 10, '1': 20 })"))?; + let object = value + .as_object() + .ok_or_else(|| JsNativeError::typ().with_message("Expected object"))?; + + let keys = object.own_property_keys(&mut context)?; + + assert_eq!( + keys, + &[PropertyKey::from(1), PropertyKey::from(js_string!("x"))] + ); + + let mut values = Vec::new(); + for key in keys { + values.push(object.get(key, &mut context)?); + } + + assert_eq!(values, &[JsValue::from(20), JsValue::from(10)]); + + Ok(()) +}