效果图:
//源数组const arrList = [{"id": 1,"code": "001","name": "第一个","parentCode": "",},{"id": 2,"code": "00101","name": "第一个的二级","parentCode": "001",},{"id": 3,"code": "0010101","name": "第一个的三级","parentCode": "00101",},{"id": 4,"code": "0010102","name": "第一个的三级","parentCode": "00101",},{"id": 3,"code": "002","name": "第二个","parentCode": "",},{"id": 6,"code": "00201","name": "第二个的二级","parentCode": "002",},{"id": 7,"code": "0020101","name": "第二个的三级","parentCode": "00201",},{"id": 8,"code": "0020102","name": "第二个的三级","parentCode": "00201",}]const listToTreeRegion = (list, fromKey = 'code', parentId = 'parentCode') => {const data = JSON.parse(JSON.stringify(list)); //浅浅的拷贝一份const result = []; //组装的结果const map = {}; //查找if (!Array.isArray(data)) return result;for (const item of data) {if (!map[item[fromKey]]) {map[item[fromKey]] = {...item,children: []};}const parent = map[item[parentId]];if (parent) {// 如果item有parent,则将其添加到parent的children中 parent.children.push(map[item[fromKey]]);} else {// 如果没有parent,则将其添加到树的根级别 result.push(map[item[fromKey]]);}}return result;}const treeList = listToTreeRegion(arrList);console.log(treeList)