样例数据:var jsonData = [{"id":"1","pid":"0","name":"家用电器"}, {"id":"4","pid":"1","name":"大家电"}, {"id":"5","pid":"1","name":"生活电器"}, {"id":"2","pid":"0","name":"服饰"}, {"id":"3","pid":"0","name":"化妆"}, {"id":"7","pid":"4","name":"空调"}, {"id":"8","pid":"4","name":"冰箱"}, {"id":"9","pid":"4","name":"洗衣机"}, {"id":"10","pid":"4","name":"热水器"}, {"id":"11","pid":"3","name":"面部护理"}, {"id":"12","pid":"3","name":"口腔护理"}, {"id":"13","pid":"2","name":"男装"}, {"id":"14","pid":"2","name":"女装"}, {"id":"15","pid":"7","name":"海尔空调"}, {"id":"16","pid":"7","name":"美的空调"}, {"id":"19","pid":"5","name":"加湿器"}, {"id":"20","pid":"5","name":"电熨斗"}]
2、实现方法:
function creatTreeData(list){
var clonelist = JSON.parse(JSON.stringify(list))
var result =clonelist.filter(function(father){
var childlist = clonelist.filter(function(child){
return father.id= child.pid
})
if(childlist.length>0){
father.children=childlist
}
return father.pid ==0
})
return result
}
3、方法封装
function treeData(list,id,pid,children){
var clone = JSON.parse(JSON.stringify(list))
return clone.filter(function(father){
var childlist =clone.filter(function(child){
return father[id]==child[pid]
})
if(childlist.length>0){
father[children]=childlist
}
return father[pid]==0
})
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML>
<HEAD>
<TITLE>New Document </TITLE>
<SCRIPT LANGUAGE="JavaScript">
var t="{'firstName': 'cyra', 'lastName': 'richardson', 'address': { 'streetAddress': '1 Microsoft way', 'city': 'Redmond', 'state': 'WA', 'postalCode': 98052 },'phoneNumbers': [ '425-777-7777','206-777-7777' ] }"
var jsonobj=eval('('+t+')')
alert(jsonobj.firstName)
alert(jsonobj.lastName)
var t2="[{name:'zhangsan',age:'24'},{name:'lisi',age:'30'},{name:'wangwu',age:'16'},{name:'tianqi',age:'7'}] "
var myobj=eval(t2)
for(var i=0i<myobj.lengthi++){
alert(myobj[i].name)
alert(myobj[i].age)
}
var t3="[['<a href=# onclick=openLink(14113295100,社旗县国税局桥头税务所,14113295100,d6d223892dc94f5bb501d4408a68333d,swjg_dm)>14113295100</a>','社旗县国税局桥头税务所','社旗县城郊乡长江路西段']]"
//通过eval() 函数可以将JSON字符串转化为对象
var obj = eval(t3)
for(var i=0i<obj.lengthi++){
for(var j=0j<obj[i].lengthj++){
alert(obj[i][j])
}
}
/*
//stringifier 函数的作用跟 parse 相反, 用来将一个js对象转换为 JSON 文本。
var jsonText = JSON.stringify(obj)
alert(jsonText)
//如果基于安全的考虑的话,最好是使用一个 JSON 解析器。 一个 JSON 解析器将只接受 JSON 文本。所以是更安全的。
var myObject = JSON.parse(myJSONtext, filter)
//可选的 filter 参数将遍历每一个value key 值对, 并进行相关的处理。如:
//如
myData = JSON.parse(text, function (key, value) {
return key.indexOf('date') >= 0 ? new Date(value) : value })
//stringifier 函数的作用跟 parse 相反, 用来将一个js对象转换为 JSON 文本。
var myJSONText = JSON.stringifier(myObject)
*/
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>