如何将 JavaScript 对象转换为 Map[String,String]?
How do I turn a JavaScript object into Map[String,String]?
在 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]
?
关键是它不是 Map
,这就是它不起作用的原因。但是是一个js.Dictionary
。因此,请将其用于您的 asInstanceOf
,如果您确实需要 Scala Map
,请在其上使用 toMap
函数:
val a2b = js.Dynamic.global.a2b.asInstanceOf[js.Dictionary[String]].toMap
在 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]
?
关键是它不是 Map
,这就是它不起作用的原因。但是是一个js.Dictionary
。因此,请将其用于您的 asInstanceOf
,如果您确实需要 Scala Map
,请在其上使用 toMap
函数:
val a2b = js.Dynamic.global.a2b.asInstanceOf[js.Dictionary[String]].toMap