【发布时间】:2017-05-29 01:51:00
【问题描述】:
我有一个对象数组,其中每个元素都包含一个字符串,表示它在树结构中的位置。根据该数据生成树视图(例如使用基本的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>
-
食物
- 面包
- 健康
-
水果
- 苹果
- 香蕉
-
蔬菜
- 胡萝卜
-
水果
-
不良
- 汉堡
- 热狗
-
国家
-
欧洲
- 德国
-
亚洲
- 中国
-
欧洲
【问题讨论】:
标签: javascript arrays reactjs tree