How to convert JavaScript object to Dart Map? How to convert JavaScript object to Dart Map? dart dart

How to convert JavaScript object to Dart Map?


Here's an adapter to handle a JsObject like a Map<String, dynamic> :

import 'dart:collection' show Maps;import 'dart:js';class JsMap implements Map<String,dynamic> {  final JsObject _jsObject;  JsMap.fromJsObject(this._jsObject);  operator [](String key) => _jsObject[key];  void operator []=(String key, value) {    _jsObject[key] = value;  }  remove(String key) {    final value = this[key];    _jsObject.deleteProperty(key);    return value;  }  Iterable<String> get keys => context['Object'].callMethod('keys', [_jsObject]);  // use Maps to implement functions  bool containsValue(value) => Maps.containsValue(this, value);  bool containsKey(String key) => keys.contains(key);  putIfAbsent(String key, ifAbsent()) => Maps.putIfAbsent(this, key, ifAbsent);  void addAll(Map<String, dynamic> other) {    if (other != null) {      other.forEach((k,v) => this[k] = v);    }  }  void clear() => Maps.clear(this);  void forEach(void f(String key, value)) => Maps.forEach(this, f);  Iterable get values => Maps.getValues(this);  int get length => Maps.length(this);  bool get isEmpty => Maps.isEmpty(this);  bool get isNotEmpty => Maps.isNotEmpty(this);}


You can generate json and parse it:

    Map map = JSON.decode(       context['JSON'].callMethod(           'stringify',           [context['map']]       )    );


If you want to do it deeply and handle also other cases then simple maps AND preserve functions (unlike the json solution) then use this simple function:

_toDartSimpleObject(thing) { if (thing is js.JsArray) {  List res = new List();  js.JsArray a = thing as js.JsArray;  a.forEach((otherthing) {    res.add(_toDartSimpleObject(otherthing));  });  return res; } else if (thing is js.JsObject) {  Map res = new Map();  js.JsObject o = thing as js.JsObject;  Iterable<String> k = js.context['Object'].callMethod('keys', [o]);   k.forEach((String k) {   res[k] = _toDartSimpleObject(o[k]);  });  return res; } else {  return thing; }}