如何用 js 递归输出树型

时间:2024-03-23 18:35:20
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body> <script> var data = [
{ id: 1, title: 'a', pid: 0 },
{ id: 2, title: 'a1', pid: 1 },
{ id: 3, title: 'a11', pid: 2 },
{ id: 4, title: 'a12', pid: 2 },
{ id: 5, title: 'a2', pid: 1 },
{ id: 6, title: 'a21', pid: 5 }
];
function fn(data, pid) {
var result = [], temp;
for (var i in data) {
if (data[i].pid == pid) {
result.push(data[i]);
temp = fn(data, data[i].id);
if (temp.length > 0) {
data[i].children = temp;
}
}
}
return result;
}
//console.log(fn(data, 0)); Array.prototype.ToTreeJson = function (pid) {
var result = [], temp;
for (var i in this) {
if (this[i].pid == pid) {
result.push(this[i]);
temp = fn(this, this[i].id);
if (temp.length > 0) {
this[i].children = temp;
}
}
}
return result;
} var p = data.ToTreeJson(0);
</script>
</body>
</html>