父子關係的陣列和樹形結構資料相互轉化
阿新 • • 發佈:2020-07-19
父子關係的陣列和樹形結構資料相互轉化
/** * @description 父子關係的陣列轉換成樹形結構資料 * @param data * @returns {*} */ export function translateDataToTree(data) { const parent = data.filter( (value) => value.parentId === "undefined" || value.parentId == null ); const children = data.filter( (value) => value.parentId !== "undefined" && value.parentId != null ); const translator = (parent, children) => { parent.forEach((parent) => { children.forEach((current, index) => { if (current.parentId === parent.id) { const temp = JSON.parse(JSON.stringify(children)); temp.splice(index, 1); translator([current], temp); typeof parent.children !== "undefined" ? parent.children.push(current) : (parent.children = [current]); } }); }); }; translator(parent, children); return parent; } /** * @description 樹形結構資料轉換成父子關係的陣列 * @param data * @returns {[]} */ export function translateTreeToData(data) { const result = []; data.forEach((item) => { const loop = (data) => { result.push({ id: data.id, name: data.name, parentId: data.parentId, }); const child = data.children; if (child) { for (let i = 0; i < child.length; i++) { loop(child[i]); } } }; loop(item); }); return result; }
參考:
https://github.com/chuzhixin/vue-admin-beautiful
順便推薦一下這個vue-admin-beautiful,一款基於vue+element-ui的絕佳的中後臺前端開發管理框架(基於vue/cli 4 最新版,同時支援電腦,手機,平板),他同時是擁有100+頁面的大型vue前端單頁應用。