Search code examples
kotlinkotlin-js-interop

Assigning properties to a javascript object using dynamic property names


I would like to do something like this but I have no idea, and I can't use js() to insert any dynamic data into because js() only takes constant string parameters (or is there a way to do that?)

    val doc: dynamic = Any()
    doc._id = name
    data.forEach {
        it.forEach { entry ->
            // need to set property of the doc using entry.key as the property name with entry.value
        }
    }

Solution

  • you can using indexed access just like as javascript bracket access notation, for example:

    val doc: dynamic = Any()
    doc._id = name
    data.forEach {
        it.forEach { entry ->
          // v--- kotlin process the brackets []= as a set operator
          doc[entry.key] = entry.value;
        }
    }