【发布时间】:2017-12-04 04:39:48
【问题描述】:
鉴于这个简单的对象数组:
var allPaths = [
{path: "/", component: 'cmp-1'},
{path: "/my-cool-list/", component: 'cmp-2'},
{path: "/my-cool-list/this-is-card-1", component: 'cmp-3'},
{path: "/my-cool-list/this-is-card-2", component: 'cmp-4'},
{path: "/blog/", component: 'cmp-5'},
{path: "/blog/2017/01/this-is-card-3", component: 'cmp-6'},
{path: "/blog/2017/02/this-is-card-4", component: 'cmp-7'},
{path: "/recettes/", component: 'cmp-8'},
{path: "/recettes/this-is-card-5", component: 'cmp-9'},
{path: "/recettes/this-is-card-6", component: 'cmp-10'}
]
需要产生这个输出:
[
{
path: "/", component: 'cmp-1'
},
{
path: "/my-cool-list",
component: 'cmp-2',
children: [
{path: "/this-is-card-1", component: 'cmp-3'},
{path: "/this-is-card-2", component: 'cmp-4'}
]
},
{
path: "/blog",
component: 'cmp-5',
children: [
{
path: "/2017",
children: [
{
path: "/01",
children: [
{path: "/this-is-card-3", component: 'cmp-6'}
]
},
{
path: "/02",
children: [
{path: "/this-is-card-4", component: 'cmp-7'}
]
}
]
}
]
},
{
path: "/recettes",
component: 'cmp-8',
children: [
{path: "/this-is-card-5", component: 'cmp-9'},
{path: "/this-is-card-6", component: 'cmp-10'}
]
},
]
我发现这样做的一种方法是:
- 遍历
allPaths中的每个对象 - 为每个路径创建一个有效的输出(就像只提供了这个路径)
- 将生成的对象推入名为
tree的数组中 - ...冲洗并重复...
- 然后将生成的
tree深度合并为一个唯一的。
代码看起来像这样fiddle here:
let tree = []
// Recursive Tree Builder
const buildTree = (pathArray, ...others) => {
var currentToken = pathArray.shift()
var arr = []
if (pathArray.length>0) {
arr.push( {path: '/'+currentToken, children: []} )
arr[0].children = buildTree(pathArray, ...others)
} else {
arr.push( Object.assign( {path: '/'+currentToken}, others[0] ))
}
return arr;
}
// For each object in `allPaths`, build a tree
allPaths.map( page => {
let {path, ...rest} = page
let res = buildTree(path.split('/').slice(1), rest)
tree.push(res[0])
})
// external code to deeply merge each objects in `tree` (external library: no need to put the code here but you got the point)
我想应该有一种方法可以懒惰地构建最终输出,而不需要在最后进行另一个合并操作:就像在旅途中构建最终树而无需中间存储 + 另一个操作。
为了进一步缩小问题范围,我尝试即时构建树,但在尝试将条目推送到树中的精确位置时遇到了困难。例如,保持对tree[0].children[0].children[0].children[0] ... 的引用让我很烦恼,因为我不知道我会找到相关路径的深度,或者children 是否会存在于这个级别。
一个伪代码(我想)是:
- 一一遍历
allPaths对象
(假设第一个遍历的对象的路径类似于/blog/level-2)
在
tree中搜索path中的第一级(例如:/blog中的/blog/level-2)没有找到?然后,将对象推入树中
这条路径有更多的层次(比如
/blog/level-2)?.......是吗?深入一层 (
/level-2) 到children并从第 3 步开始重复.......不是吗?将级别重置为 0。break
现在我很难实现这些级别跟踪:
- 我不知道如何在给定路径的情况下轻松查询tree:/blog/level-2 可能位于tree[2].children[14] 或tree[32].children[57],我很难查询它,但还要存储此信息以供以后使用。
有什么想法吗?
【问题讨论】:
-
看来是angular2路由器定义。为什么不直接手动编写文件而不是创建函数
-
不抱歉,这与 Angular 无关。 :)
标签: javascript arrays ecmascript-6