使用本机javascript/Html创建Html树视图

使用本机javascript/Html创建Html树视图,javascript,html,css,Javascript,Html,Css,我需要使用本机javascript从已经创建的对象创建一个HTML/CSS树视图,如示例所示 请建议, BR您可以首先构建嵌套结构,然后使用递归方法也从该数据创建html,如果当前元素具有children属性,则可以使用该children数组作为数据参数再次调用该函数 var data=[{“name”:“container-1”,“type”:“container”,“description”:“container description”},{“name”:“category-1”,“ty

我需要使用本机javascript从已经创建的对象创建一个HTML/CSS树视图,如示例所示

请建议,


BR

您可以首先构建嵌套结构,然后使用递归方法也从该数据创建html,如果当前元素具有children属性,则可以使用该children数组作为数据参数再次调用该函数

var data=[{“name”:“container-1”,“type”:“container”,“description”:“container description”},{“name”:“category-1”,“type”:“grid-1”,“type”:“grid”,“parent”:“category-1”},{“name”:“chart-1”,“type”:“chart”,“parent”:“category-1”},{“name”:“container-2”,“type”:“container”},{“name”:“category-2”,“type”:“类别”,“父项”:“容器-2”},{“名称”:“类别-3”,“类型”:“类别”,“父项”:“容器-2”},{“名称”:“网格-2”,“类型”:“网格”,“父项”:“类别-2”},{“名称”:“图表-2”,“类型”:“图表”,“父项”:“类别-2”},{“名称”:“网格-3”,“类型”:“网格”,“父项”:“类别-3”}]
函数toTree(数据,pid=未定义){
返回数据。减少((r,e)=>{
如果(pid==e.parent){
常量obj={…e}
const children=toTree(数据,例如名称)
if(children.length)obj.children=children;
r、 推送(obj)
}
返回r
}, [])
}
函数toHtml(数据,isRoot=true){
const ul=document.createElement('ul')
如果(!isRoot){
ul.classList.add('hide')
}
data.forEach(e=>{
让isVisible=isRoot;
const li=document.createElement('li')
const text=document.createElement('span')
const button=document.createElement('按钮')
如果(如儿童){
button.textContent='+'
li.appendChild(按钮)
}
text.textContent=e.name
李.儿童(文本)
如果(如儿童){
const children=toHtml(e.children,false)
李.儿童(儿童)
addEventListener('click',function(){
if(isRoot){
isVisible=!isVisible
}
button.textContent=isVisible?'+':'-'
children.classList.toggle('hide')
如果(!isRoot){
isVisible=!isVisible
}
})
}
ul.儿童(李)
})
返回ul;
}
常数树=总树(数据)
常量html=toHtml(树)
document.body.appendChild(html)
.hide{
显示:无;
}
钮扣{
右边距:10px;

}
你今天问了同样的问题。那么,对于生成html树,你有答案吗:)?谢谢@Nenad Vracar,但我需要它带+/-,意思是当按+时,它会扩展相关节点。相同的for-,最小化内容。如第一张图所示,你可以尝试
const obj=Object.assign({},e)