js list轉tree
//------------------------------------List Convert to Tree ----------------------------------------------------// /** * 將list裝換成tree 封裝到JqueryUtils * @param {Object } id 節點主ID * @param {Object } pId 父節點ID * @param {Object } list list數據 * @return {Node} - 自定義Node樹節點 * @author Jason - jasonandy@hotmail.com */ function listToTree(id,pId,list){ convertToNodeList(list); /** * @param {} list list * @param {} pId 父節點 * @return {Boolean} 是否存在父節點 * @description now.id = other.pid other 的父節點為 noew */ function exists(list, pId){ for(var i=0; i<list.length; i++){ if (list[i][id] == pId){ return true; } } return false; } /** * 樹節點數據 最終數據結構 * @type Node treeNode */ var nodes = []; /** * 將所有的節點數據裝入List * @type Number */ for(var i=0; i<list.length; i++){ var row = list[i]; if (!exists(list, row[pId])){//now.pid != new.id nodes.push(row);//new ids } } /** * 父節點 * @type Node */ var pNodes = []; /** * 將所有的子節點數據裝入 pNodes * @type pNodes */ for(var i=0; i<nodes.length; i++){ pNodes.push(nodes[i]); } /** * 循環處理所有節點數據並進行封裝 */ while(pNodes.length){ /** * 把數組的第一個元素從其中刪除,並返回第一個元素的值 * the parent node */ var node = pNodes.shift(); /** * * get the children nodes */ for(var i=0; i<list.length; i++){ var row = list[i]; /** * 取出list所有數據 比較處理 * * 這里可以定制化 Node 節點數據結構 * { * "isActive": true, * "isRoot": true, * "title": "標題1", * "items": [ * { * "text": "內容1" * }, * { * "text": "內容2" * } * ] * } */ if (row[pId] == node[id]){ /** * 如果有items 直接放入 */ if (node.items){ node.items.push(row); } else { node.items = [row]; } pNodes.push(row); } } } return nodes; } /** * Node 節點數據封裝 * @param {} list 轉為map結構數據 * @return {} list 需要轉換的list */ function convertToNodeList(list){ $.each(list,function(i,e){ e['title'] = e.NAME; e['isRoot'] = (e.PARENT_ID == '-1'); e['isActive'] = (e.ENABLE_STATUS == '01'); }) return list; } //------------------------------------List Convert to Tree End----------------------------------------------------//