样例数据: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
})
}
不一样。_son文件代码是一种轻量级的数据交换格式,主要是为了跨平台交流数据用的,仅仅是一种数据形式。而js文件代码是表示类的实例。
_秸咧湎喔ㄏ喑桑涤_son数据格式是从js对象中演变出来的,它是js的一个子集。区别与json可以跨平台传播速度快,而js不能实现传播。
?
1、先定义一个json变量。
2、然后定义这个变量的值,其实一个json对象就是一个obj对象。
3、要添加json对象的元素,直接使用数组下标方式,添加键和值就行了。
4、要为json对象添加对象,我们可以先创建一个对象。
5、然后也是使用数组下标方式,为其赋值为新的对象变量就行了。
6、在浏览器里,我们就可以看到这个json对象了,而且新加的元素和对象都已经在里面了。