For example, we have this structure:
data class Item(
val city: String,
val name: String
)
val structure = mapOf("items" to listOf(
Item("NY", "Bill"),
Item("Test", "Test2"))
)
And I want to get this object in Javascript:
var structure = {
"items": [
{
"city": "NY",
"name": "Bill"
},
{
"city": "Test",
"name": "Test2"
}
]
}
How we could convert map
from Kotlin to dynamic
type with such structure in Javascript?
I find only this explicit way:
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
}
I know that is possible to do this also with serialization/deserialization, but I think it will be slower and with some overhead.
Does anybody know simple way to covert Kotlin object
to plain Javascript object
(dynamic
Kotlin type)?