JS,实现一维数组JSON树结构的转换

JavaScript021

JS,实现一维数组JSON树结构的转换,第1张

1、方法思路使用js数组自带的filter()方法;数据格式要求,父子节点通过,Id,ParentId进行关联。默认父结节id为0。

样例数据: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

})

}

//数组转json串var arr = [1,2,3, { a : 1 } ]

JSON.stringify( arr )

//json字符串转数组var jsonStr = '[1,2,3,{"a":1}]'

JSON.parse( jsonStr )

方法如下:

12345678910 function tojson(arr){  

if(!arr.length) return null 

var i = 0 

len = arr.length,    array = []

for(i<leni++){    

array.push({"projectname":arr[i][0],"projectnumber":arr[i][1]})   }

return JSON.stringify(array) } 

JavaScript一种直译式脚本语言,是一种动态类型、弱类型、基于原型的语言,内置支持类型。它的解释器被称为JavaScript引擎,为浏览器的一部分,广泛用于客户端的脚本语言,最早是在HTML(标准通用标记语言下的一个应用)网页上使用,用来给HTML网页增加动态功能。

在1995年时,由Netscape公司的Brendan Eich,在网景导航者浏览器上首次设计实现而成。因为Netscape与Sun合作,Netscape管理层希望它外观看起来像Java,因此取名为JavaScript。但实际上它的语法风格与Self及Scheme较为接近。

为了取得技术优势,微软推出了JScript,CEnvi推出ScriptEase,与JavaScript同样可在浏览器上运行。为了统一规格,因为JavaScript兼容于ECMA标准,因此也称为ECMAScript。