1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| const list = [ { id: 1, parentId: null }, { id: 2, parentId: null }, { id: 12, parentId: 1 }, ];
function bullTree (list) { const temp = {}; const tree = []; for (let item of list) { temp[item.id] = item; } for (let i in temp) { // 当前节点 const currentNode = temp[i]; if (currentNode.parentId) { // 非顶层节点 const currentParentNode = temp[currentNode.parentId]; if (currentParentNode) { // 当前节点的父节点存在 if (!currentParentNode.children) { currentParentNode.children = []; } currentParentNode.children.push(currentNode); } } else { // 顶层节点 tree.push(currentNode); } } }
|