[JS-INTEROP] "for in" and "for of" loop of dynamic objects

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?

thx in advance

1 Like

The equivalent Kotlin code would be:

val map = mapOf( a to 1, b to 2 )
for(key in map.keys) { }

which I suspect is not an answer to your actual question. Note that you can also do the following:

for((key, value) in map) { ... }
1 Like

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(…)

1 Like

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.


Object.keys only enumerates the objects own properties whilst for in includes the prototype chain so still doesn’t solve the problem

1 Like