两种效果:
- 只取叶子
- 全部都要
思路:1 判断有子节点就递归,2传递res接收结果,3 把父path一层层传下去,使用args接收不定参数
let arr = [
{
path: '1',
children: [
{ path: '/1.1', children: [{ path: '/1.1.1' }, { path: '/1.1.2 ' }] },
{ path: '/1.2 ' },
],
},
{
path: '2',
children: [
{ path: '/2.1', children: [{ path: '/2.1.1' }, { path: '/2.1.2 ' }] },
{ path: '/2.2 ' },
],
},
{ path: '3', children: [{ path: '/3.1' }, { path: '/3.2 ' }] },
]
只取叶子
fun(arr)
function fun(arr) {
let res = []
funSub(arr, res, null)
console.log(res)
}
function funSub(arr, res, ...args) {
arr.forEach((item) => {
if (item.children) {
funSub(item.children, res, item, ...args)
} else {
let tmp = item.path
if (args.length > 0) {
args.forEach((arg) => {
if (arg) {
tmp = arg.path + tmp
}
})
}
res.push({ path: item.path, tmp })
}
})
}
效果
[
{ path: '/1.1.1', tmp: '1/1.1/1.1.1' },
{ path: '/1.1.2 ', tmp: '1/1.1/1.1.2 ' },
{ path: '/1.2 ', tmp: '1/1.2 ' },
{ path: '/2.1.1', tmp: '2/2.1/2.1.1' },
{ path: '/2.1.2 ', tmp: '2/2.1/2.1.2 ' },
{ path: '/2.2 ', tmp: '2/2.2 ' },
{ path: '/3.1', tmp: '3/3.1' },
{ path: '/3.2 ', tmp: '3/3.2 ' }
]
全部都要
fun(arr)
function fun(arr) {
let res = []
funSub(arr, res, null)
console.log(res)
}
function funSub(arr, res, ...args) {
arr.forEach((item) => {
let tmp = item.path
if (args.length > 0) {
args.forEach((arg) => {
if (arg) {
tmp = arg.path + tmp
}
})
}
res.push({ path: item.path, tmp })
if (item.children) {
funSub(item.children, res, item, ...args)
}
})
}
效果
[
{ path: '1', tmp: '1' },
{ path: '/1.1', tmp: '1/1.1' },
{ path: '/1.1.1', tmp: '1/1.1/1.1.1' },
{ path: '/1.1.2 ', tmp: '1/1.1/1.1.2 ' },
{ path: '/1.2 ', tmp: '1/1.2 ' },
{ path: '2', tmp: '2' },
{ path: '/2.1', tmp: '2/2.1' },
{ path: '/2.1.1', tmp: '2/2.1/2.1.1' },
{ path: '/2.1.2 ', tmp: '2/2.1/2.1.2 ' },
{ path: '/2.2 ', tmp: '2/2.2 ' },
{ path: '3', tmp: '3' },
{ path: '/3.1', tmp: '3/3.1' },
{ path: '/3.2 ', tmp: '3/3.2 ' }
]