树形结构的数据:
let tree = [
{
id: 1,
label: "一级 2",
children: [
{
id: 3,
pid: 1,
label: "二级 2-1",
children: [
{
id: 4,
pid: 3,
label: "三级 3-1-1",
},
{
id: 5,
pid: 3,
label: "三级 3-1-2",
},
],
},
{
id: 2,
pid: 1,
label: "二级 2-2",
children: [
{
id: 6,
pid: 2,
label: "三级 3-2-1",
},
{
id: 7,
pid: 2,
label: "三级 3-2-2",
},
],
},
],
},
]
方法
function parentTree(arr, id) {
var temp = [];
var callback = function (nowArr, id) {
for (var i = 0; i < nowArr.length; i++) {
var item = JSON.parse(JSON.stringify(nowArr[i]));
if (item.id === id) {
if(item.children && item.children.length > 0) {
item.children = temp
temp = [];
}
temp.push(item);
callback(arr, item.pid);
break;
} else {
if (item.children) {
callback(item.children, id);
}
}
}
};
callback(arr, id);
return temp;
}
parentTree(tree, 5);
结果
[{"id":1,"label":"一级 2","children":[{"id":3,"pid":1,"label":"二级 2-1","children":[{"id":5,"pid":3,"label":"三级 3-1-2"}]}]}]