let dataList = [{
name: "太老爷",
id: "001",
pId: null,
}, {
name: "大爷",
id: "002",
pId: "001",
}, {
name: "二大爷",
id: "003",
pId: "001",
}, {
name: "大爸",
id: "004",
pId: "002",
}, {
name: "二爸",
id: "006",
pId: "002",
}, {
name: "老叔",
id: "005",
pId: "003",
}, {
name: "二叔",
id: "007",
pId: "003",
}, {
name: "三叔",
id: "008",
pId: "003",
}, {
name: "张三",
id: "009",
pId: "006",
}]
console.log(setTreeData(dataList))
function setTreeData(list) {
const cloneData = JSON.parse(JSON.stringify(list));
return cloneData.filter(father => {
const childrenList = cloneData.filter(child => father.id === child.pId);
childrenList.length ? father.children = childrenList : [];
return !father.pId;
})
}
|