JavaScript递归遍历json数组并层级显示菜单

一.首先定义一个json数组。

      pid:父类id

      id:主键ID


	var treeData = [
	   {id:8,name:"王八",sex:1,pid:7},
	   {id:7,name:"赵薇",sex:1,pid:4},
	   {id:6,name:"晴儿",sex:1,pid:4},
	   {id:5,name:"王八",sex:1,pid:4},
	   {id:1,name:'yan',sex:1,pid:0},
	   {id:2,name:'zhang',sex:2,pid:1},
	   {id:3,name:'lisi',sex:1,pid:2},
	   {id:4,name:'zhaoliu',sex:2,pid:0}
	];

二.最终输出结果:

JavaScript递归遍历json数组并层级显示菜单_第1张图片

三.代码具体实现如下:

    //用递归的方式生成层级数据
	var getChildren = function(data,root){
		var children = [];
		for(var i = 0; i < data.length; i++){
			if(root == data[i].pid){
				data[i].children = getChildren(data,data[i].id);
				children.push(data[i]);
			}
		}
		return children;
	}
	var childData = getChildren(treeData,0);

    
    //用递归的方式显示层级数据
    var str = "";
    var forData = function(childData,str){
    	str += "|______";
    	for(var i=0;i";
                 forData(obj.children, str);
    		}else{
    			 document.getElementById("os").innerHTML +=str + obj.name +"
"; } } } forData(childData,str);

 

你可能感兴趣的:(前端)