Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert JavaScript object to Dart Map?

I am looking for some reverse of new JsObject.jsify. Something, that would convert javascript Object back to Dart Map Is there something like that available?

I know that I can use JSON conversion to string, but this does not address transfer of Objects containing functions, Dart objects, Dom Elements, etc... Is there any better method?

like image 875
Samuel Hapak Avatar asked Oct 30 '13 19:10

Samuel Hapak


People also ask

How do you turn an object into a dart Map?

Using Iterable forEach() method We can convert Dart List of Objects to Map in another way: forEach() method. var map = {}; list. forEach((customer) => map[customer.name] = {'email': customer.

How do you change an object to a Map in flutter?

You can try this: var data = { "key1": "value1", "key2": "value2", "key3": "value3", }; var myMap = Map<String, dynamic>. from(data); print(myMap); With dynamic in Map<String, dynamic> we can have the values of the map of any type.

Can we convert Map to object in Javascript?

To convert a Map to an object, call the Object. fromEntries() method passing it the Map as a parameter, e.g. const obj = Object. fromEntries(map) . The Object.


1 Answers

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);
}
like image 76
Alexandre Ardhuin Avatar answered Oct 22 '22 13:10

Alexandre Ardhuin