如何将JavaScript对象转换为Dart Map?

时间:2013-10-30 19:05:50

标签: javascript dart

我正在寻找new JsObject.jsify的反向。有什么东西可以将javascript Object转换回Dart Map是否有可用的东西?

我知道我可以使用JSON转换为字符串,但这并不涉及Object包含函数,Dart对象,Dom Elements等的转移......有没有更好的方法?

5 个答案:

答案 0 :(得分:5)

这是一个处理JsObject的适配器,如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);
}

答案 1 :(得分:5)

如果你想深入处理并处理其他情况,那么简单的映射和保留函数(与json解决方案不同)然后使用这个简单的函数:

_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;
 }
}

答案 2 :(得分:4)

您可以生成json并解析它:

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

答案 3 :(得分:0)

以上所有答案对我都没有用。

matanlurey提供了一个似乎更新的解决方案,实际上对我有用(Dart SDK 1.24.0),在这里:

https://stackoverflow.com/a/41291503/5280562

简而言之,它使用新的package:js代替dart:js

答案 4 :(得分:0)

将递归转换任何JS对象到Dart映射,列表或标量值:

/// js_interop.dart
import 'dart:js';

/// Converts the specified JavaScript [value] to a Dart instance.
dynamic convertToDart(value) {
  // Value types.
  if (value == null) return null;
  if (value is bool || value is num || value is DateTime || value is String) return value;

  // JsArray.
  if (value is Iterable) return value.map(convertToDart).toList();

  // JsObject.
  return new Map.fromIterable(getKeysOfObject(value), value: (key) => convertToDart(value[key]));
}

/// Gets the enumerable properties of the specified JavaScript [object].
List<String> getKeysOfObject(JsObject object) => (context['Object'] as JsFunction).callMethod('keys', [object]);

用法:

/// config.js
window.$environment = 'staging';
window.$config = {
  name: 'FooBar',
  params: {
    assets: ['css', 'js'],
    forceSsl: true
  }
};

/// main.dart
import 'dart:js' as js;
import 'js_interop.dart';

void main() {
  var environment = convertToDart(js.context[r'$environment']);
  assert(environment is String);
  assert(environment == 'staging');

  var config = convertToDart(js.context[r'$config']);
  assert(config is Map<String, dynamic>);
  assert(config.length == 2);

  assert(config['name'] is String);
  assert(config['name'] == 'FooBar');

  assert(config['params'] is Map<String, dynamic>);
  assert(config['params'].length == 2);

  assert(config['params']['forceSsl'] is bool);
  assert(config['params']['forceSsl'] == true);

  assert(config['params']['assets'] is List<String>);
  assert(config['params']['assets'].length == 2);
  assert(config['params']['assets'].first == 'css');
  assert(config['params']['assets'].last == 'js');
}

警告:创建的实例不反映原始JS对象的更改。如果您需要此功能,Alexandre Arduin的答案是正确的。