样例数据: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、数组转换为树结构
对象数组一定要按照id值排好序,每个对象id唯一,但不同对象的parentId可以相同,可根据parentId找到其父元素。
2、将树结构转换为数组
这里用到广度优先搜索和队列这种数据结构
最近在做一个移动的页面需求,这个里面需要支付付款,那么就要用到密码。而这个密码又要有要有一个动画,这个时候我们就要把数组中6位数字传化成一个数字。这个数字就password然后把密码传入到后端的服务器去判断是否密码正确,从而达到支付成功。
具体实现过程如下。
具体步骤是:
第一步,把数字数组用tostring()方法转换成字符串数组,在打印台打印后,我们发现有逗号间隔,这个时候我们就要想到去除逗号。
第二步,去除逗号,我们就会联想到用空字符串替换,这个时候有挤幼用到正则表达式。
第三步,把数字字符串转化成数字,只需要用到类型转换就可以了。
成功后,我们就可以进入支付成功页面。