/*
* 組裝樹形函數 (樹形有無限層級)
* 根據parent_id 將數據組裝到每個元素children屬性當中 parent_id = 0 為最頂級元素
*/
/* * js實現無限層級樹形數據結構(創新算法) * 根據parent_id 將數據組裝到每個元素children屬性當中 parent_id = 0 為最頂級元素 * Note: 把扁平數據轉成樹形數據 */ const data = [ { id: 1, name: '模塊1', parent_id: 0, children: [] }, { id: 2, name: '子模塊1-1', parent_id: 1, children: [] }, { id: 3, name: '子模塊1-2', parent_id: 1, children: [] }, { id: 4, name: '模塊3', parent_id: 0, children: [] }, { id: 5, name: '子模塊3-1', parent_id: 4, children: [] }, { id: 6, name: '子模塊1-2-1', parent_id: 3, children: [] }, ]; function getNestedChildren(arr, parent) { const res = []; for (let item of arr) { if (item.parent_id === parent) { const children = getNestedChildren(arr, item.id); if (children.length) { item.children = children; } res.push(item); } } return res; } const arr = [ { id: 1, name: '模塊1', parent_id: 0, children: [ { id: 2, name: '子模塊1-1', parent_id: 1, children: [] }, { id: 3, name: '子模塊1-2', parent_id: 1, children: [{ id: 6, name: '子模塊1-2-1', parent_id: 3, children: [] }], }, ], }, { id: 4, name: '模塊3', parent_id: 0, children: [{ id: 5, name: '子模塊3-1', parent_id: 4, children: [] }] }, ]; // 反向操作 function getFlattenChildren(arr = []) { let res = []; arr.forEach(item => { res.push(item); if (item.children) { res.push(...helper(item.children)); } }); return res; }