创建数据
const list = [];
for (let i = 0; i < 1000; i += 200) {
if (i === 0) {
list.push({ id: i - 1, age: '年龄-' + (i - 1) });
list.push({ id: i, age: '年龄-' + i, parentId: -1 });
} else {
for (let index = i - 199; index <= i; index++) {
list.push({ id: index, age: '年龄-' + index, parentId: i - 200 });
}
}
}
数据如图:
转换为children树结构
function treeData(source, id, parentId, children){
let cloneData = JSON.parse(JSON.stringify(source));
return cloneData.filter(father=>{
let branchArr = cloneData.filter(child => father[id] == child[parentId]);
branchArr.length>0 ? father[children] = branchArr : '';
return father[parentId] == -1; //返回第一层 我这里是-1 实际应用根据自己项目情况修改
})
}
const data = treeData(list,'id','parentId','children')
转换后data如图,