我有一个项目列表,这些项目可以有孩子,孩子也可以有孩子。我使用的应用程序接口在单个对象数组中返回这些项的列表,并提供一个path属性来使用该列表并按您选择的方式对其进行组织。每个子进程从0001开始向path添加一个额外的递增-000n。我不知道如何使用path值将对象列表组织成嵌套数组,其中每一项都有自己的children[]数组。
我使用的是Typescript/JS和Kotlin (Android框架)。
我已经尝试解决这个问题一段时间了,我很感激社区对这个问题的一些意见。希望我已经解释得足够好了,谢谢!
示例:
|--group (0001)
|--item (0001-0001)
|--item (0001-0001-0001)
|--item (0001-0001-0001-0001)
|--item (0001-0001-0001-0002)
|--item (0001-0002)
|--item (0001-0002-0001)
|--item (0001-0002-0001-0001)
|--item (0001-0002-0001-0001-0001)
|--item (0001-0002-0001-0002)
|--item (0001-0003)
|--group (0002)
|--item (0002-0001)有效负载:
{
"items": [
{
"name": "cameras",
"type": "group",
"path": "0001"
},
{
"name": "camera-1",
"type": "equipment",
"path": "0001-0001"
},
{
"name": "charger",
"type": "power",
"path": "0001-0001-0001"
},
{
"name:": "cable",
"type": "power",
"path": "0001-0001-0001-0001"
},
{
"name": "adapter",
"type": "power",
"path": "0001-0001-0001-0002"
},
{
"name": "camera-2",
"type": "equipment",
"path": "0001-0002"
},
// etc
{
"name": "lights",
"type": "group",
"path": "0002"
}
// etc
]
}首选结果:
{
"items": [
{
"name": "cameras",
"type": "group",
"path": "0001",
"children": [
{
"name": "camera-1",
"type": "equipment",
"path": "0001-0001",
"children": [
{
"name": "charger",
"type": "power",
"path": "0001-0001-0001",
"children": [
{
"name:": "cable",
"type": "power",
"path": "0001-0001-0001-0001"
},
{
"name": "adapter",
"type": "power",
"path": "0001-0001-0001-0002"
}
]
}
]
},
{
"name": "camera-2",
"type": "equipment",
"path": "0001-0002",
// children as above
}
]
},
{
"name": "lights",
"type": "group",
"path": "0002",
// children as above
}
]
}发布于 2021-05-30 21:32:52
在构建项目树时,可以使用映射来按项目的路径存储项目。下面是一个例子:
data class Item(
val name: String,
val type: String,
val path: String,
val children: MutableList<Item> = mutableListOf(),
)
val itemsList = <flat list of items, parsed from json>
val pathMap = mutableMapOf<String, Item>()
val itemsTree = mutableListOf<Item>()
for (item in itemsList) {
pathMap[item.path] = item
if ('-' in item.path) {
val parentPath = item.path.substringBeforeLast('-')
val parent = pathMap[parentPath]
if (parent != null) {
parent.children += item
}
} else {
itemsTree += item
}
}在这里,itemsList是扁平层次结构中的原始条目列表,而itemsTree是仅包含顶级条目的列表,每个条目都有一个包含子条目的children属性。然而,这确实要求所有“父母”在itemsList中出现在其任何孩子之前,但可以很容易地进行修改,以说明不是这种情况。
我不确定您想要的是Kotlin还是TypeScript,但是概念很容易在两者之间互换,您所需要的只是一个类似地图的数据结构。
https://stackoverflow.com/questions/67761587
复制相似问题