树json数据结构
转化后的普通json数据格式
方法一
function treeTransArray(tree, key) {//通过树结构返回普通json数组
return tree.reduce(function(con, item) {
var callee = arguments.callee;
con.push(item);
if (item[key] && item[key].length >0)
item[key].reduce(callee, con);
return con;
}, []).map(function(item){
item[key] = [];
return item;
})
}
严格模式下调用此方法可能会报错 arguments.callee;
可修改如下
function treeTransArray(tree, key) {//通过树结构返回普通json数组
return tree.reduce(function itemTree(con, item) {
con.push(item);
if (item[key] && item[key].length >0)
item[key].reduce(itemTree, con);
return con;
}, []).map(function(item){
item[key] = [];
return item;
})
}
**调用方法**
var selList=[{}] // 创建一个数组 默认的第一个元素为对象
selList[0]=node //node 为树形json , childrenList为 key
var dataArr=treeTransArray(selList,'childrenList');
方法二
使用ztree 自带方法
下载ztree.js ;
```javascript
var newTree=$.fn.zTree.getZTreeObj("TargetTree");//获取树
var Nodes=newTree.getNodes();//拿到树形的json树节点(最上一张图的节点)
var act=newTree.transformToArray(Nodes); //ztree自带将json 树结构转化普通json的方法
反转 普通json转化树形json
//“childData” 为children 数组;
//idstr 自身code id
//pidstr 父级的code或者id
//list 普通形式的数组
function arrayTransTree(list,idstr,pidstr){
try {
let result = [],temp = {};
for(let i = 0; i < list.length; i++){
temp[list[i][idstr]]=list[i];//将nodes数组转成对象类型
}
for(let j=0; j<list.length; j++){
let tempVp = temp[list[j][pidstr]]; //获取每一个子对象的父对象
if(tempVp){//判断父对象是否存在,如果不存在直接将对象放到第一层
if(!tempVp["childData"]) tempVp["childData"] = [];//如果父元素的childData对象不存在,则创建数组
tempVp["childData"].push(list[j]);//将本对象压入父对象的childData数组
}else{
result.push(list[j]);//将不存在父对象的对象直接放入一级目录
}
}
return result;
} catch (error) {
console.log(error)
}
},