我有一个对象数组,其中每个元素都包含一个表示其在树结构中位置的字符串。基于该数据生成 TreeView (例如使用基本的 ul
/li
标记)的简单方法是什么?
事先不知道树结构的深度,所以递归可能是解决方案?
我正在使用 React,但我想这个问题并不是真正特定于 React 的,因此通用 JS 甚至伪代码都会有很大帮助。
示例数据:
[
{
"name": "banana",
"path": "food.healthy.fruit",
// ... may contain other parameters
},
{
"name": "apple",
"path": "food.healthy.fruit"
}
{
"name": "carrot",
"path": "food.healthy.vegetable"
},
{
"name": "bread",
"path": "food"
},
{
"name": "burger"
"path": "food.unhealthy"
},
{
"name": "hotdog"
"path": "food.unhealthy"
},
{
"name": "germany",
"path": "country.europe"
},
{
"name": "china",
"path": "country.asia"
}
]
期望的结果:
<ul>
<li>
food
<ul>
<li>bread</li>
<li>healthy
<ul>
<li>
fruit
<ul>
<li>apple</li>
<li>banana</li>
</ul>
</li>
<li>
vegetable
<ul>
<li>carrot</li>
</ul>
</li>
</ul>
</li>
<li>
unhealthy
<ul>
<li>burger</li>
<li>hotdog</li>
</ul>
</li>
</ul>
</li>
<li>
country
<ul>
<li>
europe
<ul>
<li>germany</li>
</ul>
</li>
<li>
asia
<ul>
<li>china</li>
</ul>
</li>
</ul>
</li>
</ul>
- >
食物
- 面包
- 健康
- >
水果
- 苹果
- 香蕉
- >
蔬菜
- 胡萝卜
- >
水果
- >
不良
- 汉堡
- 热狗
- >
国家
- >
欧洲
- 德国
- >
亚洲
- 中国
- >
欧洲
最佳答案
首先按路径分组。
您可以通过遍历源数据并按点符号为每个项目拆分路径来执行此操作。然后像这样通过键将每个项目存储在一个对象中
store[country] = store[country] || {}
store[country][europe] = store[country][europe] || []
store[country][europe].push(germany)
然后在根级别获取对象的所有键并递归渲染所有项目。这是一些伪代码:
function render(store){
let keys = Object.keys(store)
let ul = document.createElement('ul')
for (var i = 0; i < keys.length; i++){
let key = keys[i]
if (typeof store[key] === 'object') {
let li = document.createElement('li')
//create a branch, return it with our render function and append to current level
li.appendChild(render(store[key]))
} else {
// create html presentation for all items under the current key
let li = document.createElement('li')
}
ul.appendChild(li)
}
return ul
}
关于javascript - 将对象数组渲染为树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41638873/