function treeTolist(treeNodes, opt) { if (!opt) { opt = {}; opt.key = "id"; opt.parent = "pid"; opt.children = "children"; } var NodeList = []; function appenChildren(nodes) { for (var i = 0; i < nodes.length; i++) { var node = nodes[i]; //如果没有上层节点那么就是根节点 if (node.parentNode == null) { node.Level = 0; node[opt.parent]=0; } //判断是否有子节点 if (node[opt.children] && node[opt.children].length > 0) { //所有子节点 for (var k = 0; k < node.children.length; k++) { node[opt.children][k][opt.parent] = node[opt.parent]; node[opt.children][k].Level = node.Level + 1; node[opt.children][k].parentNode = node; } appenChildren(node.children); } if(node.hasOwnProperty("parentNode")) delete node.parentNode; if(node.hasOwnProperty(opt.children)) delete node[opt.children]; NodeList.push(node); } } appenChildren(treeNodes); return NodeList; } var TreeNodes = [ { "id": 1, "parent": 0, "children": [ { "id": 2, "parent": 1, "children": [ { "id": 3, "parent": 2, "children": [ { "id": 4, "parent": 3, "children": [ { "id": 5, "parent": 4, "children": [ { "id": 6, "parent": 5, "children": [ { "id": 7, "parent": 6, "children": [ { "id": 8, "parent": 7, "children": [ { "id": 9, "parent": 8, "children": [ { "id": 10, "parent": 9, "children": [] } ] } ] } ] } ] } ] } ] } ] } ] } ] } ]; var treeNodeList = treeTolist(TreeNodes, { key: "id", parent: "pid", children: "children" }); console.log(JSON.stringify(treeNodeList));
技术交流QQ群:15129679