window.onload = function () {
var data = [{ "id": "01", "parentId": "0", "name": "后端编程语言" },
{ "id": "02", "parentId": "0", "name": "前端编程语言" },
{ "id": "03", "parentId": "0", "name": "嵌入式开发" },
{ "id": "0101", "parentId": "01", "name": ".NET" },
{ "id": "010101", "parentId": "0101", "name": "C#语言" },
{ "id": "010102", "parentId": "0101", "name": "F#语言" },
{ "id": "01010102", "parentId": "010101", "name": "C#2.0" },
{ "id": "01010101", "parentId": "010101", "name": "C#1.0" },
{ "id": "0102", "parentId": "01", "name": "Java" },
{ "id": "010201", "parentId": "03", "name": "Android" },
{ "id": "0102012323", "parentId": "0103", "name": "G0.1" },
{ "id": "0103", "parentId": "01", "name": "Go" },
{ "id": "0201", "parentId": "02", "name": "Javascript" },
{ "id": "0202", "parentId": "02", "name": "Typescript" }
];
console.log("============从上往下查找================")
let resultArray = [];
let getChilds = function (pid, parent) {
let childs = [];
for (const child of data) {
if (child.parentId === pid) {
childs.push(child);
}
}
if (childs.length <= 0) {
if (parent) {
delete parent.children;
}
return;
}
for (const c of childs) {
let v;
if (!parent) {
v = { lable: c.name, children: [] };
resultArray.push(v);
} else {
v = { lable: c.name, children: [] };
parent.children.push(v);
}
getChilds(c.id, v);
}
};
// getChilds("0");
// console.log(resultArray)
console.log("============从下往上查找================")
let rootReusltArray = [];
let getRoot = function (id) {
if (id == '0') {
return;
};
for (const item of data) {
if (item.id === id) {
rootReusltArray.push(item.name);
getRoot(item.parentId);
return;
}
}
}
getRoot('010101');
console.log(rootReusltArray.reverse())
}
原创文章,作者:dweifng,如若转载,请注明出处:https://blog.ytso.com/275356.html