例如,我们有这样的结构:
data class Item(
val city: String,
val name: String
)
val structure = mapOf("items" to listOf(
Item("NY", "Bill"),
Item("Test", "Test2"))
)
我想在 Javascript 中获取这个对象:
var structure = {
"items": [
{
"city": "NY",
"name": "Bill"
},
{
"city": "Test",
"name": "Test2"
}
]
}
我们如何map
从 Kotlin转换为dynamic
Javascript 中具有这种结构的类型?
我发现只有这种明确的方式:
fun Map<String, Any>.toJs(): dynamic {
val result: dynamic = object {}
for ((key, value) in this) {
when (value) {
is String -> result[key] = value
is List<*> -> result[key] = (value as List<Any>).toJs()
else -> throw RuntimeException("value has invalid type")
}
}
return result
}
fun List<Any>.toJs(): dynamic {
val result: dynamic = js("[]")
for (value in this) {
when (value) {
is String -> result.push(value)
is Item -> result.push(value.toJs())
else -> throw RuntimeException("value has invalid type")
}
}
return result
}
fun Item.toJs(): dynamic {
val result: dynamic = object {}
result["city"] = this.city
result["name"] = this.name
return result
}
我知道使用序列化/反序列化也可以做到这一点,但我认为它会更慢并且有一些开销。
有人知道将 Kotlinobject
转换为纯 Javascript object
(dynamic
Kotlin 类型)的简单方法吗?