取一个对象数组并用 JavaScript 把以上 JSON 转换成一个树状结构
假设,我们有一个这样的对象数组 −
const arr = [
{
"parentIndex": '0' ,
"childIndex": '3' ,
"parent": "ROOT",
"child": "root3"
},
{
"parentIndex": '3' ,
"childIndex": '2' ,
"parent": "root3" ,
"child": "root2"
},
{
"parentIndex": '3' ,
"childIndex": '1' ,
"parent": "root3" ,
"child": "root1"
}
];我们需要编写一个 JavaScript 函数来读取一个这样的对象数组。然后,函数应该使用递归并把上述 JSON 转换成一个树状结构。
树状结构看起来像 −
nodeStructure: {
text: { name: "root3" },
children: [
{
text: { name: "root2" }
},
{
text: { name: "root1" }
}
]
}
};示例
代码如下 −
const arr = [
{
"parentIndex": '0' ,
"childIndex": '3' ,
"parent": "ROOT",
"child": "root3"
},
{
"parentIndex": '3' ,
"childIndex": '2' ,
"parent": "root3" ,
"child": "root2"
},
{
"parentIndex": '3' ,
"childIndex": '1' ,
"parent": "root3" ,
"child": "root1"
}
];
const partial = (arr = [], condition) => {
const result = [];
for (let i = 0; i < arr.length; i++) {
if(condition(arr[i])){
result.push(arr[i]);
}
}
return result;
}
const findNodes = (parentKey,items) => {
let subItems = partial(items, n => n.parent === parentKey);
const result = [];
for (let i = 0; i < subItems.length; i++) {
let subItem = subItems[i];
let resultItem = {
text: {name:subItem.child}
};
let kids = findNodes(subItem.child , items);
if(kids.length){
resultItem.children = kids;
}
result.push(resultItem);
}
return result;
}
console.log(JSON.stringify(findNodes('ROOT', arr), undefined, 4));输出
控制台中的输出如下 −
[
{
"text": {
"name": "root3"
},
"children": [
{
"text": {
"name": "root2"
}
},
{
"text": {
"name": "root1"
}
}
]
}
]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP