Browse Source

Implement object keys access (#3832)

pull/3838/head
Haled Odat 7 months ago committed by GitHub
parent
commit
6febf7eda0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
  1. 10
      core/engine/src/object/operations.rs
  2. 31
      examples/src/bin/properties.rs

10
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<Vec<PropertyKey>> {
self.__own_property_keys__(context)
}
/// `Call ( F, V [ , argumentsList ] )`
///
/// # Panics

31
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(())
}
Loading…
Cancel
Save