我正在尝试从平面对象数组构建树数组。 类别字段被构造为数组,因为它可以有 n 个类别
let data = [
{
category: [
"Kat1"
],
otherFields: [
"Document 1"
]
},
{
category: [
"Kat1"
],
otherFields: [
"Document 2"
]
},
{
category: [
"Test",
"Test 2"
],
otherFields: [
"Document 1"
]
},
{
category: [
"Test",
"Test 2",
"Test 3",
"Test 4",
"Test 5",
"Test 6",
"Test 7",
"Test 8",
"Test 9",
"Test 10",
"Test 11"
],
otherFields: [
"Document 1"
]
}
]
应该是
let tree = [
{
label: "Kat1",
children: [
{ label: "Document 1" },
{ label: "Document 2" },
]
},
{
label: "Test",
children: [
{
label: "Test 2",
children: [
{ label: "Document 1" },
{
label: 'Test 3',
children: [
{
label: 'Test 4',
children: [
...
]
}
]
}
]
},
]
}
]
有没有解决类似问题的文章、链接?在我上次的尝试中,我只得到了每次在文档和子类别中都失败的主要类别
我相信您必须使用父字段或子字段来扩展您的对象。这些可以引用数组中父/子的索引。例如,GLTF 格式就是这样做的。
但是,如果您必须保持不变地使用该数据结构,那么您可以迭代数组,为每个类别创建一个新分支,并使用类别作为键将它们保存在映射中。然后,您可以通过再次迭代数组并将每个类别的子数组附加到地图的相应值来创建树。