JS数组 父子关系 生成 对象
JS数组 父子关系 生成 对象
JS数组(父子关系)数据如下:
var data = [{"id":"1","parentId":"0","name":"主目录"}, {"id":"2","parentId":"1","name":"1级目录:2"}, {"id":"3","parentId":"1","name":"1级目录:3"}, {"id":"4","parentId":"2","name":"2级目录:4"}, {"id":"5","parentId":"3","name":"2级目录:5"}, {"id":"6","parentId":"3","name":"2级目录:6"}, {"id":"7","parentId":"6","name":"3级目录:7"}, {"id":"8","parentId":"7","name":"4级目录:8"}, {"id":"9","parentId":"5","name":"3级目录:9"}, {"id":"10","parentId":"9","name":"4级目录:10"} ];
JS数组 ID关系图,如下:
|-0 |-2 |-4 |-3 |-5 |-9 |-10 |-6 |-7 |-8
JS 转换代码:
var getJsonTree=function(data,parentId){ var itemArr=[]; for(var i=0;i<data.length;i++){ var node=data[i]; //data.splice(i, 1) if(node.parentId==parentId ){ var newNode={id:node.id,title:node.name,nodes:getJsonTree(data,node.id)}; itemArr.push(newNode); } } return itemArr; }
使用方法:
var jsonArray = getJsonTree(data,'0'); console.log(jsonArray);
这是输出结果.
[{"id":"1","title":"主目录","nodes":[{"id":"2","title":"1级目录:2","nodes":[{"id":"4","title":"2级目录:4","nodes":[]}]},{"id":"3","title":"1级目录:3","nodes":[{"id":"5","title":"2级目录:5","nodes":[{"id":"9","title":"3级目录:9","nodes":[{"id":"10","title":"4级目录:10","nodes":[]}]}]},{"id":"6","title":"2级目录:6","nodes":[{"id":"7","title":"3级目录:7","nodes":[{"id":"8","title":"4级目录:8","nodes":[]}]}]}]}]}]
<注意:上面的输出中,即使nodes为空数组,也将该属性输出了,如果nodes为空,不进行输出,使用下面代码.>
下面的代码做了判断,如果数组为空,将不给对象添加nodes属性
var getJsonTree=function(data,parentId){ var itemArr=[]; for(var i=0;i<data.length;i++){ var node=data[i]; //data.splice(i, 1) if(node.parentId==parentId ){ var newNode={id:node.id,title:node.name}; var result = getJsonTree(data,node.id); if(result.length > 0) { newNode['nodes'] = result } itemArr.push(newNode); } } return itemArr; }
输出结果:
[{"id":"1","title":"主目录","nodes":[{"id":"2","title":"1级目录:2","nodes":[{"id":"4","title":"2级目录:4"}]},{"id":"3","title":"1级目录:3","nodes":[{"id":"5","title":"2级目录:5","nodes":[{"id":"9","title":"3级目录:9","nodes":[{"id":"10","title":"4级目录:10"}]}]},{"id":"6","title":"2级目录:6","nodes":[{"id":"7","title":"3级目录:7","nodes":[{"id":"8","title":"4级目录:8"}]}]}]}]}]
若现在就觉得失望无力,未来那么远你该怎么扛 —— 致自己