gpt4 book ai didi

Javascript 递归(树结构)

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:40:22 36 4
gpt4 key购买 nike

我有以下 json :

var jsonObj = [
{
"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 中使用 Recursion 将上述 json 转换为树结构。树结构看起来像:

nodeStructure: {
text: { name: "root3" },
children: [
{
text: { name: "root2" }
},
{
text: { name: "root1" }
}
]
}
};

最佳答案

使用以下代码:

var jsonObj = [
{
"parentIndex": '0' ,
"childIndex": '3' ,
"parent": "ROOT",
"child": "root3"
},
{
"parentIndex": '3' ,
"childIndex": '2' ,
"parent": "root3" ,
"child": "root2"
},
{
"parentIndex": '3' ,
"childIndex": '1' ,
"parent": "root3" ,
"child": "root1"
}
];

function filter(array,condition){
var result = [];
for (var i = 0; i < array.length; i++) {
if(condition(array[i])){
result.push(array[i]);
}
}
return result;
}


function getChilds(parentKey,items){
var subItems = filter(items,function(n){return n.parent === parentKey});
var result = [];
for (var i = 0; i < subItems.length; i++) {
var subItem = subItems[i];
var resultItem = {
text: {name:subItem.child}
};
var kids = getChilds(subItem.child , items);
if(kids.length){
resultItem.children = kids;
}
result.push(resultItem);
}
return result;
}


var rootItems = getChilds('ROOT',jsonObj);

关于Javascript 递归(树结构),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43710456/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com