数据结构constinitData[{id:1,parentId:0,name:1},{id:2,parentId:0,name:2},{id:3,parentId:1, // 数据结构const initData [{id: 1,parentId: 0,name: "1"},{id: 2,parentId: 0,name: "2"},{id: 3,parentId: 1,name: "3"},{id: 4,parentId: 2,name: "
// 数据结构const initData [{id: 1,parentId: 0,name: "1"},{id: 2,parentId: 0,name: "2"},{id: 3,parentId: 1,name: "3"},{id: 4,parentId: 2,name: "4"},{id: 5,parentId: 3,name: "5"},{id: 6,parentId: 4,name: "6"},{id: 7,parentId: 6,name: "7"}]
执行的方法如下
function cloneTree(score, parentId 0) {let tree [];score.map((item)>{if(item.parentId parentId) {// 递归寻找item.children cloneTree(score, item.id);tree.push(item);}});return tree;}// 将数据 打印出来console.log(makeTree(initData));
参考
JS实现平级数组变成树级结构