欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

js 递归遍历n维json数组的算法

shiping1 的头像

JS树形递归实例

下面的代码是从实际项目中AJAX的回调部分 copy 出来的,使用了JS的递归,文本格式为JSON:

var l=json.length;
var arr = [];
for(var i = 0; i < l; i++){
	(function(){
		var jsonArray =arguments[0];
		for(var k in jsonArray){
			if(k.indexOf('children') != -1 && jsonArray[k] != null){
				arguments.callee(jsonArray[k]);
			}
			else{
				if(k == 'name' || k == 'children'){
					arr.push(jsonArray[k]+'');
				}
			}
		}
	})(json[i]);
}	

JSON如下所示:

[{"id":"001","name":"上海市浦东新区","children":{"id":"002","name":"上海市徐汇区"}}]
来自 http://www.cnblogs.com/georgewing/archive/2010/05/18/1738037.html

递归循环JSON


2013-10-15      0 个评论       作者:qq873113580
收藏    我要投稿
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
  
/// <summary
/// JsonHelper 的摘要说明 
/// </summary
public class JsonHelper 
    /// <summary
    /// 转换JSON对象 
    /// </summary
    /// <param name="company"></param
    /// <returns></returns
    public static string ConvertToJson(Company company) 
    
        string json = "CompanyName:\"" + company.CompanyName + "\",ContactName:\"" + company.ContactName + "\",City:\"" + company.City + "\",CustomerID:\"" + company.CustomerID + "\",children:{0}"; 
        return json; 
    
  
    /// <summary
    /// 转换JSON对象集合,包含子集,递归加载 
    /// </summary
    /// <param name="companyList"></param
    /// <returns></returns
    public static string ConvertToJson(List<Company> companyList) 
    
        string json = "["; 
        //获取第一级目录 
        List<Company> rootList = companyList.Where(x => string.IsNullOrEmpty(x.Pid)).ToList<Company>(); 
        foreach (Company root in rootList) 
        
            string js = ConvertToJson(root); 
            string children=""; 
            children = DiGui(companyList, children, root.CustomerID); 
            json += "{"+string.Format(js, children) + "},"; 
        
        if (json.LastIndexOf(",") < 1
        
            json += "]"; 
        
        else 
        
            json = json.Substring(0, json.Length - 1) + "]"; 
        
        return json.Replace(",children:[]", ""); 
    
  
    /// <summary> 
    /// 递归调用添加包含子集的JSON数组 
    /// </summary
    private static string DiGui(List<Company> companyList,string children,string pid) 
    
        children = "["; 
        List<Company> childerList = companyList.Where(x => x.Pid.ToUpper() == pid.ToUpper()).ToList<Company>(); 
        foreach (Company item in childerList) 
        
            string js = ConvertToJson(item); 
            string cd = ""; 
            cd = DiGui(companyList, cd, item.CustomerID); 
            children += "{"+string.Format(js, cd) + "},"; 
        
        if (children.LastIndexOf(",") < 1) 
        
            children += "]"; 
        
        else 
        
            children = children.Substring(0, children.Length - 1) + "]"; 
        
        return children; 
    
  
      
  
}












来自  http://www.2cto.com/kf/201310/250013.html



学习js对象和数组的递归调用,用来遍历json数据  不指定

justwinit 2008-7-22 16:26   |  |   
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>一个使用到for...in循环的Javascript示例</title>
</head>
<body>
<script type="text/javascript">
var data = {
    products : [ { name: "Linu", desc: "computer",     
                   price: 1000, quantity: 100, alert:null },
                 { name: "ipod", desc: "music player", 
                   price:  200, quantity: 200, alert:"on sale now!" },
                 { name: "cinema display", desc: "screen",       
                   price:  800, quantity: 300, alert:"best deal!" } ],
    customer : { first: "John", last: "Public", level: "gold" }
};





  function isArray(a) { 
    if(typeof a =="undefined"||null==a)
    {
      return false;
    }
    else
    {  
      return a.sort ? true : false; 
    }
  }
function printObj(obj,depth,Attr)
{
  if(typeof depth=="undefined"){depth=0;}
  if(typeof Attr=="undefined"){Attr="";}
/*
  var space="";
  for(var i=0;i<=depth;i++)
  {
    space+="&nbsp;"
  }
  if(""!=Attr)
  {
    document.write(space+Attr+":<br />");
  }

  */

    if(isArray(obj))
  {
    for(var i=0;i<obj.length;i++)
    {
      printObj(obj[i],depth++,i);
    }
  }
  else{
    
    if(typeof obj=="undefined")
    {
    }else if(typeof obj=="string"||typeof obj=="number" ||typeof obj=="boolean")
    {
      
      //document.write(space+"&nbsp;"+obj+"<br />");
      document.write("&nbsp;"+obj+"<br />");
    }else
    {    
      for(var p in obj)
      {
        var eachValue=obj[p];
        printObj(eachValue,depth++,p);
      }

    }
  }

}

  printObj(data);
</script>
</body>
</html>

作者:justwinit@向东博客 专注WEB应用 构架之美 --- 构架之美,在于尽态极妍 | 应用之美,在于药到病除
地址:http://justwinit.cn/post/1154/
版权所有。转载时必须以链接形式注明作者和原始出处及本声明!

来自 http://justwinit.cn/post/1154/

 



数据格式:
var treeData=[
   {"name":"剑侠世界",
    "columns":[
           {
    "name":"新闻中心",
"columns":[
  {
   "name":"新闻",
   "parentId":2
   },
  {
   "name":"公告",
   "parentId":2  
  }
],
"parentId":1
   },
           {
    "name":"玩家文选",
"columns":[
  {"name":"门派攻略","parentId":2},
  {"name":"玩家心情","parentId":2}
],
"parentId":1
   },
           {
    "name":"游戏资料",
"columns":[
  {"name":"游戏资料0","parentId":2},
  {"name":"游戏资料1","parentId":2}
],
"parentId":1
   }        
          ],
    "parentId":0
   },
   {"name":"剑侠世界1",
    "columns":[
           {
    "name":"新闻中心1",
"columns":[
  {"name":"新闻1"},
  {"name":"公告1"}
]
   },
           {
    "name":"玩家文选1",
"columns":[
  {"name":"门派攻略1"},
  {"name":"玩家心情1"}
]
   },
           {
    "name":"游戏资料1",
"columns":[
  {"name":"游戏资料01"},
  {"name":"游戏资料01"}
]
   }        
          ],
"parentId":0
   }   
];

自己写了一个遍历算法,但是没有达到我想要得效果,把所有节点的数据都打印出来,请高手指教下,谢谢啦

function creatHtml(obj,str){
var j,ob;
for(var i=0;i<obj.length;i++)
{
if(obj[i].name)
{
 str+='<ul>'+obj[i].name+'<ul>\n';
 for(j=0;j<obj[i]["columns"].length;j++)
 {
  if (obj[i].columns[j].name) {
   str += '  <li>' + obj[i]["columns"][j].name + '</li>\n';
ob=obj[i]["columns"][j];
//alert(ob);
    creatHtml(ob,str);
}
 }
}

}
return str;
}

//测试
alert(creatHtml(treeData,""));





<div id="divmsg"></div>
<script>
var treeData=[ 
  {"name":"剑侠世界", 
    "columns":[ 
          
  "name":"新闻中心", 
"columns":[ 
  
  "name":"新闻", 
  "parentId":2 
  }, 
  
  "name":"公告", 
  "parentId":2  
  
], 
"parentId":1 
  }, 
          
  "name":"玩家文选", 
"columns":[ 
  {"name":"门派攻略","parentId":2}, 
  {"name":"玩家心情","parentId":2} 
], 
"parentId":1 
  }, 
          
  "name":"游戏资料", 
"columns":[ 
  {"name":"游戏资料0","parentId":2}, 
  {"name":"游戏资料1","parentId":2} 
], 
"parentId":1 
  }     
          ], 
    "parentId":0 
  }, 
  {"name":"剑侠世界1", 
    "columns":[ 
          
  "name":"新闻中心1", 
"columns":[ 
  {"name":"新闻1"}, 
  {"name":"公告1"} 
  }, 
          
  "name":"玩家文选1", 
"columns":[ 
  {"name":"门派攻略1"}, 
  {"name":"玩家心情1"} 
  }, 
          
  "name":"游戏资料1", 
"columns":[ 
  {"name":"游戏资料01"}, 
  {"name":"游戏资料01"} 
  }     
          ], 
"parentId":0 
  }  
]; 
 
function showAllNode(thejson){
    for(var e in thejson){
        var flag = false;// 当前元素是否是数组
        for(var ex in thejson[e]){
            flag = true;
        }
        if(flag){
            showAllNode(thejson[e]);
        }else if(thejson[e]){
            document.getElementById("divmsg").innerHTML += e + "=" + thejson[e] + "<br/>";
        }
    }
}
 
window.onload=function(){
    showAllNode(treeData);
}
</script>


呵呵。。楼上正解!分数给你了

来自 http://bbs.csdn.net/topics/300172103

 
普通分类: