Hi, I’m using Kotlin-JS, and I would like to iterate over dynamic object’s keys.
basically, I would like the Kotlin version of the following equivalent js code:
var obj={a:1,b:2};for(var key in obj)...
the following kotlin code won’t work
val obj:dynamic=...;for(key in obj)...
using Object.keys(…) is cumbersome, and I have to use js("Object") to get a reference
using reflection also seems cumbersome, and kotlin seems not having a full support for js reflection?
Hi, thanks for the reply, however it’s not answering my question.
I’m aware of mapOf(…) as well as map iteration, but the object instance obj is created by JS code not kotlin code, and has a type of dynamic. more specifically, it’s coming out of a JSON.parse(…)
Unfortunately I don’t think it is possible to achieve the for (key in obj) syntax (*). The reason is that Kotlin doesn’t allow defining extension functions with dynamic receiver.
I think your best bet would be to create a helper function:
inline fun keys(json: dynamic) = js("Object").keys(json).unsafeCast<Array<String>>()
and use it like so: for (i in keys(obj))
(*) It is possible in kotlin stdlib with some black magic. That’s why for (i in obj) compiles. Unfortunately it only supports iterating over arrays, objects with iterator function, and Kotlin Iterable descendants.