3

Is it possible to test if a javascript object contains a property?

I'm currently wrapping try/catch for each property I'd like to access. I dont think this is an efficient way to check if properties exist on the object.

1 Answer 1

2

Using try-catch is the more efficient way to check that because there's only one exchange between Dart and Js.


An other way could be to handle your javascript object like a Dart Map with :

import 'package:js/js.dart' as js;
import 'package:js/js_wrapping.dart' as jsw;

main() {
  final myProxy = ...;
  Map<String, dynamic> myProxyAsMap = jsw.JsObjectToMapAdapter.cast(proxy);
  Iterable<String> keys = myProxyAsMap.keys;
}

But it is less efficient to check if keys.contains("key") than to use the try-catch way. Moreover if you intensively use this keys consider to copy the List with a keys = myProxyAsMap.keys.toList(). Actually myProxyAsMap.keys is still baked by an underlying js array. The .toList() will create a real Dart List and prevent Dart-js exchanges.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.