2016-10-28 4 views
2

In index-dev.html ich eine lokale JavaScript-Datei laden:Wie verwandle ich ein JavaScript-Objekt in Map [String, String]?

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

map.js strukturell (nicht wörtlich) sieht wie folgt aus:

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" 
} 

ich herausgefunden, wie diese Aufgabe in Scala.js zu laden:

Jetzt ist a2b vom Typ Dynamic. Was ich will, ist Map[String,String].

Ich habe versucht, dieses:

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

aber das hat nicht funktioniert. Was soll ich tun, um eine Map[String,String] zu bekommen?

+0

Das sieht ähnlich aus: http://stackoverflow.com/questions/31655070/how-to- convert-map-zu-json-objekt-in-scala-js – gknauth

Antwort

5

Der Schlüssel ist, dass es ist nicht ein Map, weshalb es nicht funktioniert. Aber es ist ein js.Dictionary. So verwenden, die für Ihre asInstanceOf statt, und wenn Sie tatsächlich benötigen eine Scala Map, verwenden Sie die toMap Funktion auf, dass:

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

Yippee! Es funktionierte! Vielen Dank! – gknauth

Verwandte Themen