javaScript 树形数据根据指定键名溯源
/*
* 树型数据根据指定key溯源
* @param {*} keys: 指定的对象key:键名
* @param {*} lea## 标题fId : 溯源的唯一键值
* @param {*} nodes : 树型数据
*/
function findPathByLeafId(keys,leafId, nodes, path) {
if(path === undefined) {
path = [];
}
for(var i = 0; i < nodes.length; i++) {
var tmpPath = path.concat();
tmpPath.push({
...nodes[i],
children:[]
});
if(leafId == nodes[i][keys]) {
return tmpPath;
}
if(nodes[i].children) {
var findResult = findPathByLeafId(keys,leafId, nodes[i].children, tmpPath);
if(findResult) {
return findResult;
}
}
}
}
const treeData = [{
id:1,
label:"a",
children:[{
id:12,
label:"b",
children:[{
id:123,
label:"c",
children:[]
}]
}]
}]
let id = 123
//调用方式:
let a = findPathByLeafId("id", id , treeData);
console.log('溯源后的数组====>>>',a) //返回一个数组就是溯源后的[父,父,父... 子]
版权声明:本文为Cold__Star原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。