js修改父子json格式成树状结构格式

时间:2023-05-11 23:41:50

js修改父子json成树状结构

var json = [
{
"id" : "01",
"pId":""
} ,
{
"id" : "01_01",
"pId":"01"
} ,
{
"id" : "01_02",
"pId":"01"
} ,
{
"id" : "01_02_01",
"pId":"01_02"
} ,
{
"id" : "02",
"pId":""
},
{
"id" : "02-01",
"pId":"02"
},
{
"id" : "02-02",
"pId":"02"
},
{
"id" : "03",
"pId":""
},
{
"id" : "03_01",
"pId":"03"
}
];
function format(json){
var ret = [], o = {}; function add(arr, data){
var obj = {
"id": data.id,
"pId": data.pId,
"childer": []
};
o[data.id] = obj;
arr.push(obj);
} json.forEach(x => {
if(o[x.pId]){
add(o[x.pId].childer, x);
}else{
add(ret, x);
}
}); return ret;
}
console.log(format(json));