如何将JavaScript对象转换为Map [String,String]?

时间:2016-10-28 17:29:32

标签: scala.js

index-dev.html中,我加载了一个本地JavaScript文件:

<script type="text/javascript" src="map.js"></script>

map.js结构上(不是字面意思)看起来像这样:

var a2b = {
  "a": "My life closed twice before its close—",
  "b": "It yet remains to see",
  "c": "If Immortality unveil",
  "d": "A third event to me",

  "e": "So huge, so hopeless to conceive",
  "f": "As these that twice befell.",
  "g": "Parting is all we know of heaven,",
  "h": "And all we need of hell.",

  "z": "Emily Dickinson, 1830-1886"
}

我想出了如何将这个对象加载到Scala.js中:

val a2b = js.Dynamic.global.a2b

现在a2b的类型为Dynamic。我想要的是Map[String,String]

我试过了:

val a2b = js.Dynamic.global.a2b.asInstanceOf[Map[String,String]]

但这不起作用。我该怎么做才能获得Map[String,String]

1 个答案:

答案 0 :(得分:5)

关键是它不是一个Map,这就是它无法正常工作的原因。但 js.Dictionary。因此,请将其用于asInstanceOf,如果您确实需要Scala Map,请使用toMap函数:

val a2b = js.Dynamic.global.a2b.asInstanceOf[js.Dictionary[String]].toMap