ASP遞歸遍歷樹形JSON
代碼示例: function getTreeData(obj,dataid){ var rootData="",subData="",tempData=""; for(var i=0;i<obj.length;i++){ if(obj[i].parentid==dataid){ tempData='{"text": "'+obj[i].text+'","id":"' + obj[i].id + '","items": ['; subData += tempData + getTreeData(obj,obj[i].id) + ']},'; } } if(subData.length>0){ rootData=subData.substring(0,subData.length-1); } return rootData; } var jsonString='[{"id":"1","text":"A","parentid":"0"},{"id":"2","text":"B","parentid":"0"},{"id":"3","text":"C","parentid":"1"},{"id":"4","text":"D","parentid":"1"},{"id":"5","text":"E","parentid":"4"},{"id":"6","text":"F","parentid":"2"},{"id":"7","text":"G","parentid":"2"}]'; var jsonData = JSON.parse(jsonString); var resultData = '[' + getTreeData(jsonData,0) + ']'; console.log(resultData); 說明:將JSON字符串解析成對象后,通過遞歸循環解析每個節點,將子節點作為items屬性添加到父節點對象中,最終組合成完整的樹形數據。
上一篇頁面加載不上css
下一篇頁面加載時執行css樣式