javascript 将表格形式的分级数据转成JSON的树状形式
象这样的一个表格形式的数组:[{'category':'01'},{'category':'0101'},{'category':'010101'},{'category...
象这样的一个表格形式的数组:
[ {'category': '01'},
{'category': '0101'},
{'category': '010101'},
{'category': '01010101'},
{'category': '01010102'},
{'category': '01010103'},
{'category': '010102'},
{'category': '0102'},
{'category': '010201'},
{'category': '010202'},
{'category': '02'},
{'category': '020101'},
{'category': '020102'} ]
需要转换成象这样的形式的 JSON 对象:
"[{"category":"01","sub":[{"category":"0101","sub":[{"category":"010101","sub":[{"category":"01010101","sub":null},{"category":"01010102","sub":null},{"category":"01010103","sub":null}]},{"category":"010102","sub":null}]},{"category":"0102","sub":[{"category":"010201","sub":null},{"category":"010202","sub":null}]}]},{"category":"02","sub":[{"category":"020101","sub":null},{"category":"020102","sub":null}]}]"
就是表格结构到树状结构。分类下的子分类存储在 sub 属性中。 展开
[ {'category': '01'},
{'category': '0101'},
{'category': '010101'},
{'category': '01010101'},
{'category': '01010102'},
{'category': '01010103'},
{'category': '010102'},
{'category': '0102'},
{'category': '010201'},
{'category': '010202'},
{'category': '02'},
{'category': '020101'},
{'category': '020102'} ]
需要转换成象这样的形式的 JSON 对象:
"[{"category":"01","sub":[{"category":"0101","sub":[{"category":"010101","sub":[{"category":"01010101","sub":null},{"category":"01010102","sub":null},{"category":"01010103","sub":null}]},{"category":"010102","sub":null}]},{"category":"0102","sub":[{"category":"010201","sub":null},{"category":"010202","sub":null}]}]},{"category":"02","sub":[{"category":"020101","sub":null},{"category":"020102","sub":null}]}]"
就是表格结构到树状结构。分类下的子分类存储在 sub 属性中。 展开
展开全部
var data=[ {'category': '01'},
{'category': '0101'},
{'category': '010101'},
{'category': '01010101'},
{'category': '01010102'},
{'category': '01010103'},
{'category': '010102'},
{'category': '0102'},
{'category': '010201'},
{'category': '010202'},
{'category': '02'},
{'category': '020101'},
{'category': '020102'} ];
var res=data.filter((o)=>o.category.length==2).map((o)=>{
o.sub=data.filter((o1)=>o1.category.substr(0,2)==o.category&&o1.category.length==4).map((o1)=>{
o1.sub=data.filter((o2)=>o2.category.substr(0,4)==o1.category&&o2.category.length==6).map((o2)=>{
o2.sub=data.filter((o3)=>o3.category.substr(0,6)==o2.category&&o3.category.length==8);
return o2;
});
if(!o1.sub.length)o1.sub=data.filter((o2)=>o2.category.substr(0,4)==o1.category&&o2.category.length==8);
return o1;
});
if(!o.sub.length)o.sub=data.filter((o1)=>o1.category.substr(0,2)==o.category&&o1.category.length==6);
return o;
});
console.log(res);
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询