【发布时间】:2021-11-03 13:45:45
【问题描述】:
我正在尝试将数组连接到基本文件夹层次结构。
在下面的示例中,“级别 1”是最低级别,该级别没有子文件夹。 “其他级别”将在“顶级”下有许多不同的文件夹
我有数据的数组如下:
[{ id: "Top Level", outerpath: "test plan", innerpath: "Regression" },
{ id: "other level", outerpath: "Regression", innerpath: "area 1" },
{ id: "Level 1", outerpath: "area 1", innerpath: "Subarea 1" },
{ id: "Level 1", outerpath: "area 1", innerpath: "Subarea 2" },
{ id: "Level 1", outerpath: "Regression", innerpath: "area 2" }]
现在我需要对象数组中数据的串联结果如下所示:
test plan/Regression/area 1/Subarea 1
test plan/Regression/area 1/Subarea 2
test plan/Regression/area 2
但是我不知道如何开始。也许它通过匹配“innerpath”和“outpath”值的数组循环,然后将完成的数据推送到另一个数组?
任何想法都会非常有用。
更新:
为了扩展我的问题,数组是动态的,根据 API 的结果,它可能像这个数组
[{ id: "Top Level", outerpath: "test plan", innerpath: "Regression" }
{ id: "other level", outerpath: "Regression", innerpath: "area 1" }
{ id: "Level 1", outerpath: "area 1", innerpath: "Subarea 1" }
{ id: "other level", outerpath: "area 1", innerpath: "Subarea 2" }
{ id: "Level 1", outerpath: "Regression", innerpath: "area 2" }
{ id: "Top Level", outerpath: "test plan", innerpath: "other testing" }
{ id: "Level 1", outerpath: "other testing", innerpath: "other testing area 1" }
{ id: "other level", outerpath: "other testing", innerpath: "other testing area 2" }
{ id: "Level 1", outerpath: "other testing area 2", innerpath: "other testing subarea 1" }
{ id: "Level 1", outerpath: "Subarea 2", innerpath: "SubSubArea 1" }]
因此不会只有一个顶层,它可能是多个顶层,因为文件夹“测试计划”将有多个文件夹,其中一些文件夹有自己的子文件夹。
我从 API 调用的回调中整理数据的代码在这里:
let testSuiteData = res;
testSuiteData.value.forEach(async testSuiteItem => {
console.log(testSuiteItem);
if(!testSuiteItem.hasChildren === true) // Level 1
{
console.log(testSuiteItem.parentSuite.name + '/' + testSuiteItem.name)
folderHierarchy.path.push({
id: 'Level 1',
outerpath: testSuiteItem.parentSuite.name,
innerpath: testSuiteItem.name
})
}
else if(testSuiteItem.hasChildren === true ) // other levels
{
if(testSuiteItem.parentSuite.name === testSuiteItem.plan.name) // Top Level
{
console.log(testSuiteItem.parentSuite.name + '/' + testSuiteItem.name)
folderHierarchy.path.push({
id: 'Top Level',
outerpath: testSuiteItem.parentSuite.name,
innerpath: testSuiteItem.name
})
}
else{ // Other Levels
console.log(testSuiteItem.parentSuite.name + '/' + testSuiteItem.name)
folderHierarchy.path.push({
id: 'other level',
outerpath: testSuiteItem.parentSuite.name,
innerpath: testSuiteItem.name
})
}
}
console.log(folderHierarchy.path);
【问题讨论】:
-
最后一个条目(带有
area 2)不应该在other level上吗?我会尝试从输入数组创建一个树结构,然后遍历它以输出路径 -
不,因为它下面没有任何子文件夹,所以它是最低的。例如没有测试计划/Regression/area 2/"subfodlers"
-
嗨@Daniel,有机会请看看我的解决方案。它使用
do..while循环动态工作,从每个最深的innerpath值遍历到最高的ancestor。我认为首先获得最深的innerpath值列表然后从那里向后工作是明智的。如果您有任何问题,请告诉我! -
@Daniel **还值得注意的是,虽然我选择了
do..while循环,但您也可以在这里使用递归,尽管在我看来do..while循环更干净,因为它没有创建额外的不必要的函数声明。
标签: javascript arrays object