javascript实现树形结构把数组{"1", "1-3-4", "1-2", "1-2"}转变成如图的树
发布网友
发布时间:2022-05-22 02:13
我来回答
共1个回答
热心网友
时间:2023-11-26 21:23
var data = ["1", "1-3-4", "1-2", "1-2"],
result = [];
data.map(function(d){
var child = d.split("-"),
temp = result;
child.map(function(d2,i){
var _pos = pos(temp, d2);
if( _pos != -1 ){
temp = temp[_pos]["children"];
}else{
temp.push({
"id": d2,
"children": []
});
temp = temp[temp.length-1]["children"];
};
});
});
function pos(list,id){
var _pos = -1;
list.map(function(d, i){
if( d.id == id )
_pos = i;
});
return _pos;
};
console.log(JSON.stringify(result));
这个就是美化后的json结果