我有一个项目列表,这些项目可以有孩子,孩子也可以有孩子。我使用的API在单个对象数组中返回这些项的列表,并提供一个path
属性来使用该列表并按照您的选择组织它。每个子级从0001
开始向path
添加额外递增的-000n
。我不知道如何使用path
值来将对象列表组织到嵌套数组中,其中每个项都有自己的children[]
数组。
我使用的是Typescript/JS和Kotlin(安卓框架(。
经过一段时间的努力,我很感激社区对这个问题的意见。希望我解释得足够好,谢谢!
示例:
|--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
}
]
}
在构建项目树时,可以使用映射按路径存储项目。这里有一个例子:
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,但这两个概念很容易互换,你只需要一个类似地图的数据结构。