I have the following 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"
}
];
I need to convert the above json to a Tree-structure using Recursion in Javascript . The Tree-structure would look like :
nodeStructure: {
text: { name: "root3" },
children: [
{
text: { name: "root2" }
},
{
text: { name: "root1" }
}
]
}
};
use following code:
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);
You could use a single loop approach with a temporary object for collecting all nodes and the result object, wich returns the node which is the root node.
var data = [{ parentIndex: '0', childIndex: '3', parent: "ROOT", child: "root3" }, { parentIndex: '3', childIndex: '2', parent: "root3", child: "root2" }, { parentIndex: '3', childIndex: '1', parent: "root3", child: "root1" }], tree = function (data, root) { var r, o = {}; data.forEach(function (a) { o[a.childIndex] = { text: { name: a.child } }; if (o[a.childIndex] && o[a.childIndex].children) { o[a.childIndex].children = o[a.childIndex].children; } if (a.parentIndex === root) { r = o[a.childIndex]; } else { o[a.parentIndex] = o[a.parentIndex] || {}; o[a.parentIndex].children = o[a.parentIndex].children || []; o[a.parentIndex].children.push(o[a.childIndex]); } }); return r; }(data, '0'); console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.