JS 有父子关系的数组转Tree结构函数

来源:互联网 发布:淘宝免单哪里找 编辑:程序博客网 时间:2024/05/22 12:53
function convert(rows){function exists(rows, parentId){for(var i=0; i<rows.length; i++){if (rows[i].id == parentId) return true;}return false;}var nodes = [];// get the top level nodesfor(var i=0; i<rows.length; i++){var row = rows[i];if (!exists(rows, row.parentId)){nodes.push({id:row.id,text:row.name});}}var toDo = [];for(var i=0; i<nodes.length; i++){toDo.push(nodes[i]);}while(toDo.length){var node = toDo.shift();// the parent node// get the children nodesfor(var i=0; i<rows.length; i++){var row = rows[i];if (row.parentId == node.id){var child = {id:row.id,text:row.name};if (node.children){node.children.push(child);} else {node.children = [child];}toDo.push(child);}}}return nodes;}

原创粉丝点击