處理樹狀結構
阿新 • • 發佈:2021-06-29
const data = [ { id: 1, address: '安徽', parent_id: 0 }, { id: 2, address: '江蘇', parent_id: 0 }, { id: 3, address: '合肥', parent_id: 1 }, { id: 4, address: '廬陽區', parent_id: 3 }, { id: 5, address: '大楊鎮', parent_id: 4 }, { id: 6, address: '南京', parent_id: 2 }, { id: 7, address: '玄武區', parent_id: 6 }, { id: 8, address: '梅園新村街道', parent_id: 7 }, { id: 9, address: '上海', parent_id: 0 }, { id: 10, address: '黃浦區', parent_id: 9 }, { id: 11, address: '外灘', parent_id: 10 }, { id: 12, address: '安慶', parent_id: 1 }, ];
function handleTree(data, pid) { function tree(id) {const arr = []; data .filter((item) => item.parent_id === id) .forEach((item) => { arr.push({ area_id: item.id, label: item.address, children: tree(item.id), }); });return arr; } return tree(pid); } const transformData = handleTree(abc, 0); console.log(transformData);
方法2
function handleTree(arr) { const cloneData = JSON.parse(JSON.stringify(arr)); // 對源資料深度克隆 return cloneData.filter((father) => { const branchArr = cloneData.filter( (child) => father.id == child.parent_id, ); // 返回每一項的子級陣列 branchArr.length > 0 ? (father.children = branchArr) : ''; // 如果存在子級,則給父級新增一個children屬性,並賦值 return father.parent_id == 0; // 返回第一層 }); }