Skip to content

Commit

Permalink
Implement object keys access (#3832)
Browse files Browse the repository at this point in the history
  • Loading branch information
HalidOdat authored Apr 30, 2024
1 parent 4452c03 commit 6febf7e
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
10 changes: 10 additions & 0 deletions core/engine/src/object/operations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Vec<PropertyKey>> {
self.__own_property_keys__(context)
}

/// `Call ( F, V [ , argumentsList ] )`
///
/// # Panics
Expand Down
31 changes: 31 additions & 0 deletions examples/src/bin/properties.rs
Original file line number Diff line number Diff line change
@@ -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(())
}

0 comments on commit 6febf7e

Please sign in to comment.