1. 更改树形结构字段属性名称
$(function() {
treeCarding()
function treeCarding(){
var data = [
{
name: \'中国\',
children: [
{
name: \'教第三节课\',
},
{
name: \'教呼呼\',
children: [
{
name: \'大一\',
children: [
{
name: \'课程1\',
children: [
{
name: \'1231\'
},
{
name: \'121\'
}
]
},
{
name: \'课程2\',
children: [
{
name: \'1232\'
},
{
name: \'122\'
}
]
},
{
name: \'课程3\',
children: [
{
name: \'1233\'
},
{
name: \'123\'
}
]
},
]
}
]
},
{
name: \'活动\',
children:[{
name: \'aaa\'
},
{
name: \'bbb\'
}]
}
]
}
];
console.log(\"原始数据\",data);
var tree=getArray(data,0);
console.log(\"结果数据\",tree);
function getArray(data,num){
var trees =new Array();
var tempTrees,fn;
for (var i in data) {
var newData={
name1:data[i].name,
childrens:[]
}
trees.push(newData);
console.log(\'i\',trees);
console.log(\'datai\',data[i].children);
fn= getArray(data[i].children, 1);
if (data[i].children) {
trees[i].childrens=fn;
}
}
return trees
}
}
});
2.用 js 递归输出树型
var data = [
{ id: 1, : \'a\', pid: 0 },
{ id: 2, : \'a1\', pid: 1 },
{ id: 3, : \'a11\', pid: 2 },
{ id: 4, : \'a12\', pid: 2 },
{ id: 5, : \'a2\', pid: 1 },
{ id: 6, : \'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);
继续阅读与本文标签相同的文章
上一篇 :
阿里云前端周刊 - 第 28 期
下一篇 :
我发现我的数据被操纵了……
-
深入理解Java线程状态
2026-05-18栏目: 教程
-
从SpringBoot构建十万博文聊聊限流特技
2026-05-18栏目: 教程
-
《DNS攻击防范科普系列4》--遭遇DNS缓存投毒该怎么办?
2026-05-18栏目: 教程
-
进击的 Java ,云原生时代的蜕变
2026-05-18栏目: 教程
-
阿里云Kubernetes平台构建和管理实践(上)
2026-05-18栏目: 教程
