Reputation: 1666
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"]
}
]
}
]
}
]
Upvotes: 0
Views: 118
Reputation: 7172
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 })
)
}
)
}
Upvotes: 1