【发布时间】:2016-04-19 13:34:32
【问题描述】:
我正在尝试将平面数组转换为树数组,因为我将使用 jsTree 中的数据。我还需要将“名称”等键名转换为“文本”。
我想使用 lodash.js,但我是 lodash 的新手。我搜索了解决方案,但找不到适合我的情况。
那么你能帮忙吗?我的平面数组数据如下:
[
{
Id:1,
Name: 'name1',
Parent: 0
},
{
Id:2,
Name: 'name2',
Parent: 1
},
{
Id:3,
Name: 'name3',
Parent: 2
},
{
Id:4,
Name: 'name4',
Parent: 1
},
{
Id:5,
Name: 'name5',
Parent: 1
},
{
Id:6,
Name: 'name6',
Parent: 5
}
]
我想要像这样的树数据:
{
"id": 1,
"text" : "name1",
"children" : [
{
"id": 2,
"text" : "name2",
"children" : [{
"id": 3,
"text": "name3"
}]
},
{
"id": 4,
"text" : "name4"
},
{
"id": 5,
"text" : "name5",
"children" : [{
"id": 6,
"text": "name6"
}]
}
]
}
提前谢谢你
【问题讨论】:
-
数据是否已排序 - 父母是否明智?
-
@NinaScholz 是的,我们可以这么认为。
标签: javascript lodash