[
{
id: "01",
pid: "",
name: "老王",
children: []
},
{
id: "02",
pid: "01",
name: "小张",
children: []
},
{
id: "03",
pid: "02",
name: "小xx",
children: []
}
]
转成
[
{
id: "01",
pid: "",
name: "老王",
children: [
{
id: "02",
pid: "01",
name: "小张",
children: [
{
id: "03",
pid: "02",
name: "小xx"
}
]
}
]
}
]
思路:首先对原数据进行升读克隆在循环所有项在返回每一项的子级数组判断数据大于0的时候返回如果存在子级,则给父级添加一个children属性,并赋值,返回第一层,返回树形数据,返回树形数据
var data = [
{
id: "01",
pid: "",
name: "老王",
children: []
},
{
id: "02",
pid: "01",
name: "小张",
children: []
},
{
id: "03",
pid: "02",
name: "小xx",
children: []
}
]
function toTree(data) {
let cloneData = JSON.parse(JSON.stringify(data)) // 对源数据深度克隆
let tree = cloneData.filter((father) => { //循环所有项
let branchArr = cloneData.filter((child) => {
return father.id == child.pid;//返回每一项的子级数组
});
if (branchArr.length > 0) {
father.children = branchArr; //如果存在子级,则给父级添加一个children属性,并赋值
}
return father.pid == 0;//返回第一层
});
return tree; //返回树形数据
}
var tree = toTree(data);
console.log(tree);