0

I have a list of object

temp (1_id='I4509635', 2_id='I4406660', 3_id='I1111')
temp (1_id='I4509635', 2_id='I4406660', 3_id='I2222')
temp (1_id='I4509635', 2_id='I4406660', 3_id='I3333')  
temp (1_id='I4509635', 2_id='I1222233', 3_id='I14444')

and want to transform the list to an object. Like

"cat": [
    { "id_": "I4509635",
      "children": [
        {
          "id_": "I4406660",
          "children": [
            {
              id : [ "I1111", "I2222", "I3333"]
            }
          ]
        },
        {
          "id_": "I1222233",
          "children": [
            {
              "id: [ "I14444"]
            }
          ]
        }
      ]
    }
  ]
2
  • Is the depth limited to 2? plz let us know what you have tried and if you are facing any issue. Commented Jun 20, 2022 at 12:06
  • yes, depth is 2. Commented Jun 20, 2022 at 12:08

1 Answer 1

1

I'm not sure I understand your question, you result object is neither a valid Kotlin object nor valid JSON.

data class Ftemp(val Wert_1_id: String, val Wert_2_id: String, val Wert_3_id: String)

val list = listOf(
  Ftemp("I4509635", "I4406660", "I1111"),
  Ftemp("I4509635", "I4406660", "I2222"),
  Ftemp("I4509635", "I4406660", "I3333"),
  Ftemp("I4509635", "I1222233", "I14444")
)

This will give you the data structured in the same way as in your post:

val result = list
  .groupBy { it.Wert_1_id }
  .map { (key, value) -> key to value
    .map { it.Wert_2_id to it.Wert_3_id }
    .groupBy { it.first }
    .map { (key, value) -> key to value.map { it.second } }
  }

This will give you the data structured in the same way as in your post, but with the maps indicating ids and children:

val cat = list
  .groupBy { it.Wert_1_id }
  .map { (key, value) ->
    mapOf(
      "id_" to key,
      "children" to value
        .map { it.Wert_2_id to it.Wert_3_id }
        .groupBy { it.first }
        .map { (key, value) ->
          mapOf(
            "id_" to key,
            "children" to mapOf("id" to value.map { it.second })
          )
        }
    )
  }
Sign up to request clarification or add additional context in comments.

1 Comment

Also worth pointing out that while nested maps may be a reasonable representation of an arbitrary object tree, and fairly straightforward to create, they're very awkward and fragile to work with. It's usually better to convert instead to fully-fledged objects (e.g. of data classes); that gives you the benefits of type safety, compile-time type checking and inference, better performance, much more readable code, &c.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.