<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>实现一个树形结构数据加层级</title>
</head>
<body>
<script>
const Tree = [{
title: "课程1",
id: 1,
children: [{
title: "数学",
id: 100,
children: [{
title: "代数",
id: 1001
},
{
title: "几何",
id: 1002
}
]
},
{
title: "语文",
id: 101,
children: [{
title: "小学语文",
id: 1011
},
{
title: "中学语文",
id: 1012
}
]
},
{
title: "英文",
id: 102,
children: [{
title: "法文",
id: 1021
},
{
title: "英文文",
id: 1022
}
]
},
]
},
{
title: "课程2",
id: 2,
children: [{
title: "生物",
id: 200
},
{
title: "化学",
id: 201
},
]
},
{
title: "课程3",
id: 3,
children: [{
title: "政治",
id: 300
},
{
title: "地理",
id: 301
},
]
}
]
function renderTree(Tree, level = 0) {
const childs = []
for (let i = 0; i < Tree.length; i++) {
Tree[i].index = level
if (i === Tree.length - 1) {
if (Tree[i].children) childs.push(Tree[i].children)
renderTree(childs.flat(Infinity), ++level)
} else {
if (Tree[i].children) childs.push(Tree[i].children)
}
}
}
renderTree(Tree)
</script>
</body>
</html>
实现一个树形结构数据加层级
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 一、问题研究的背景和意义 在Web应用程序开发领域,基于Ajax技术的JavaScript树形组件已经被广泛使用,...
- 示例: 需求:输入 “景区” 字,希望树形结构中带有 “景区” 字的项显示,即使父节点没有,但子节点含有,父节点仍...
- 文章出处 https://yq.aliyun.com/ziliao/120224?spm=a2c4e.111554...