Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[js] 第356天 根据元素ID遍历树形结构,查找到所有父元素ID [代码] #2196

Open
haizhilin2013 opened this issue Apr 5, 2020 · 2 comments
Labels
js JavaScript

Comments

@haizhilin2013
Copy link
Collaborator

第356天 根据元素ID遍历树形结构,查找到所有父元素ID [代码]

作者:hx8321

我也要出题

[{
"orgId": 1,
"orgName": "公室1",
"parentId": 0,
"children": [{
"orgId": 2,
"orgName": "公室2",
"parentId": 1,
"children": [{
"orgId": 3,
"orgName": "公室3",
"parentId": 2,
}]
}]
}]

描述:parentId:0表示已经到顶部了,这个树形结构层级可能是多层的

@haizhilin2013 haizhilin2013 added the js JavaScript label Apr 5, 2020
@xxx135261
Copy link

`
var list = [{
"orgId": 1,
"orgName": "校长办公室1",
"parentId": 0
},{
"orgId": 2,
"orgName": "校长办公室2",
"parentId": 1,
},{
"orgId": 3,
"orgName": "校长办公室3",
"parentId": 2,
}];

function findParent(idx){
		list.forEach(item => {
		if (idx === item['orgId']){
						let pid = item['parentId']
						console.log(pid)
						findParent(pid)
		}
	})
}
findParent(3);   //2 1 0

`

@ipwangxin
Copy link

`
/*
@func 获取所有的父元素id
@params.id 传入的目标元素的id
@return [String] 所有的父元素id集合
前提条件,id为唯一键,parentId为唯一键
*/

function getParentIds(id) {
let mapTree = {};
mapList(treeData)
function mapList(list) {
list.forEach(el => {
let key = el.orgId
mapTree[key] = el
if (el.children && el.children.length) {
mapList(el.children)
}
})
}

let cur = mapTree[id]
let parentId = cur && cur.parentId
let result = []
while (parentId) {
result.push(cur.parentId)
cur = mapTree[parentId]
parentId = cur.parentId
}
if(undefined != parentId){
result.push(parentId)
}
return result
}
`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
js JavaScript
Projects
None yet
Development

No branches or pull requests

3 participants