// 根据某一个节点的过滤条件,获取其在一个森林的路径。
function getPathByKey(value, key, arr) {
let temppath = [];
try {
function getNodePath(node){
// 这里可以自定义push的内容,而不是整个node,而且这里node也包含了children
temppath.push(node);
//找到符合条件的节点,通过throw终止掉递归
if (node[key] === value) {
throw ("GOT IT!");
}
if (node.children && node.children.length > 0) {
for (var i = 0; i < node.children.length; i++) {
getNodePath(node.children[i]);
}
//当前节点的子节点遍历完依旧没找到,则删除路径中的该节点
temppath.pop();
}
else {
//找到叶子节点时,删除路径当中的该叶子节点
temppath.pop();
}
}
for (let i = 0; i < arr.length; i++) {
getNodePath(arr[i]);
}
} catch (e) {
return temppath;
}
}
使用案例
后端传来的树形结构,前端现在要根据最里面的那个id值获取路径
var tree = [
{
id: 5,
name: "root",
children: [{
id: 51,
name: "北京市",
children: [{
id: 511,
name: "西城区",
children: [{
id: 5111,
name: "xx居委会"
}]
}]
}]
},
{
id: 6,
name: "root",
children: [{
id: 61,
name: "北京市",
children: [{
id: 611,
name: "西城区",
children: [{
id: 6111,
name: "xx居委会"
}]
}]
}]
},
{
id: 7,
name: "root",
children: [{
id: 71,
name: "北京市",
children: [{
id: 711,
name: "西城区",
children: [{
id: 7111,
name: "xx居委会"
}]
}]
}]
}
]
function getPathByKey(value, key, arr) {
let temppath = [];
try {
function getNodePath(node){
temppath.push(node);
//找到符合条件的节点,通过throw终止掉递归
if (node[key] === value) {
throw ("GOT IT!");
}
if (node.children && node.children.length > 0) {
for (var i = 0; i < node.children.length; i++) {
getNodePath(node.children[i]);
}
//当前节点的子节点遍历完依旧没找到,则删除路径中的该节点
temppath.pop();
}
else {
//找到叶子节点时,删除路径当中的该叶子节点
temppath.pop();
}
}
for (let i = 0; i < arr.length; i++) {
getNodePath(arr[i]);
}
} catch (e) {
return temppath;
}
}
let res = getPathByKey(6111, 'id', tree);
console.log(res);
$ node getNode.js
[
{ id: 6, name: 'root', children: [ [Object] ] },
{ id: 61, name: '北京市', children: [ [Object] ] },
{ id: 611, name: '西城区', children: [ [Object] ] },
{ id: 6111, name: 'xx居委会' }
]
<script src="https://code.youkuaiyun.com/snippets/37.js"></script>