【发布时间】:2021-08-18 01:01:42
【问题描述】:
我有一个项目列表,这些项目可以有孩子,孩子也可以有孩子。我正在使用的 API 在单个对象数组中返回这些项目的列表,并提供一个 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
}
]
}
【问题讨论】:
标签: android json typescript kotlin recursion