var data = [
{
name: '红色集团总部',
userName: '刘备',
id: 1,
children: [
{
name: '红色集团分部1',
userName: '刘备儿子1',
id: 5,
children: [
{
name: '红色最小分部',
userName: '刘备最小儿子',
id: 14
}
]
},
{
name: '红色集团分部2',
userName: '刘备儿子2',
id: 6
}
]
},
{
name: '黄色集团总部',
userName: '张飞',
id: 2,
children: [
{
name: '黄色集团分部1',
userName: '张飞儿子1',
id: 7
},
{
name: '黄色集团分部2',
userName: '张飞儿子2',
id: 8,
children: [
{
name: '黄最小部',
userName: '张飞最小儿子',
id: 15
}
]
}
]
},
{
name: '蓝色集团总部',
userName: '沙僧',
id: 3,
children: [
{
name: '蓝色集团分部1',
userName: '沙僧儿子1',
id: 9,
children: [
{
name: '蓝色小小分部1',
userName: '沙僧小小儿子1',
id: 16
}
]
},
{
name: '蓝色集团总部2',
userName: '沙僧儿子2',
id: 10
},
{
name: '蓝色集团总部3',
userName: '沙僧儿子3',
id: 11,
children: [
{
name: '蓝色小小分部2',
userName: '沙僧小小儿子2',
id: 17
}
]
}
]
},
{
name: '绿色集团总部',
userName: '孙悟空',
id: 4,
children: [
{
name: '绿色孙悟空',
userName: '孙悟空儿子1',
id: 12,
children: [
{
name: '绿色孙悟空66',
userName: '孙悟空最最儿子',
id: 18
}
]
},
{
name: '绿色金库咒',
userName: '孙悟空儿子2',
id: 13
}
]
}
]
function getPathById(data, id) {
let arr = [], // 操作数组
res = [], // 结果 AND 是否匹配到
run = true // 运行
// data 解析
data.map(e => {
arr.push({
pid: e.id,
children: [e],
nextFnTag: true // 下一个函数的起点标识
})
})
/**
* 组查询 (无状态函数)
* @e{Array} 下一个元素
*/
function getPath(item) {
console.log(item)
if (!run) return
// 截取段落
item.nextFnTag && (res = [])
if (typeof item.id !== 'undefined') res.push(item.id)
if (item.id === id) run = false
// 下一级查询
if (item.children && item.children.length) item.children.map(getPath)
}
arr.map(getPath)
return res
}
网友评论