样例数据: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
})
}
1、javascript里面的数组都是关联数组吧?js对象的本质就是关联数组。索引数组也就是常说的数组,数组是对象,所以数组的本质也是关联数组,但通常没人这么说。2、唯一区别就是:索引数组的索引只能是0和正整数,但它是有序的。关联数组的索引很宽松,但关联数组是无序的,就这个。3、json对象是严格版本的关联数组。4、至少在chrome下,索引数组和关联数组的速度是一样的。5、索引数组的好处就是格式简单,关联数组的好处是键可以任意定义。现代浏览器中提供了JSON.stringify()方法将数组,对象转成json。JSON.stringify把一个对象转换成json字符串,JSON.parse把一个json字符串解析成对象。不支持的可以引入json2.js$.fn.stringifyArray=function(array){returnJSON.stringify(array)}$.fn.parseArray=function(array){returnJSON.parse(array)}然后调用:$("").stringifyArray(array)需要准备的材料分别是:电脑、html编辑器、浏览器。
1、首先,打开html编辑器,新建html文件,例如:index.html。
2、以追加name元素为例,在index.html的<script>标签中,输入js代码:
var names = ['Alice', 'Bob']
var json = []
for (var i = 0i <names.lengthi++) {
json[i] = {'name' : names[i]}
}
document.body.innerText = JSON.stringify(json)
3、浏览器运行index.html页面,此时会打印出追加name元素后的json数组。