Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

树结构,如何用子级id获取所有父级

data: [
    {id: 1, pid: 0, children:[ 
        {id:2, pid: 1, children:[...]}
        ]
    }
    ...
]

目前数据结构是这样的,我只拿到一个id,确定是某个分支最后一级的id,我的需求是根据这个id找回所有父级的id 目前我只会不断的那pid递归,总感觉不太好,请大神指教个优雅写法


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

答了太多次,以至于我写了一个小库来实现树相关这些功能。

安装:

npm install tree-tool

引入:

import treeTool from 'tree-tool'

使用(查找所有父节点id):

const pathList = treeTool.findPath(data, n => n.id == id) // pathList所有父级data组成的
const idList = pathList.map(n => n.id) // idList即为所求

如果你想了解是怎么实现的,可以看看下面的资源:
JS树结构操作:查找、遍历、筛选、树结构和列表结构相互转换
tree-tool树结构操作工具库


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.5k users

...