作者 fungleo

优化构建树形数据JS方法

@@ -126,23 +126,19 @@ export function praseStrEmpty(str) { @@ -126,23 +126,19 @@ export function praseStrEmpty(str) {
126 * @param {*} children 孩子节点字段 默认 'children' 126 * @param {*} children 孩子节点字段 默认 'children'
127 * @param {*} rootId 根Id 默认 0 127 * @param {*} rootId 根Id 默认 0
128 */ 128 */
129 -export function handleTree(data, id, parentId, children, rootId) {  
130 - id = id || 'id'  
131 - parentId = parentId || 'parentId'  
132 - children = children || 'children'  
133 - rootId = rootId || 0 129 +export function handleTree(data = [], id = 'id', parentId = 'parentId', children = 'children', rootId = 0) {
134 //对源数据深度克隆 130 //对源数据深度克隆
135 const cloneData = JSON.parse(JSON.stringify(data)) 131 const cloneData = JSON.parse(JSON.stringify(data))
136 //循环所有项 132 //循环所有项
137 const treeData = cloneData.filter(father => { 133 const treeData = cloneData.filter(father => {
138 - let branchArr = cloneData.filter(child => { 134 + const branchArr = cloneData.filter(child => {
139 //返回每一项的子级数组 135 //返回每一项的子级数组
140 return father[id] === child[parentId] 136 return father[id] === child[parentId]
141 }); 137 });
142 - branchArr.length > 0 ? father.children = branchArr : ''; 138 + branchArr.length && (father.children = branchArr);
143 //返回第一层 139 //返回第一层
144 return father[parentId] === rootId; 140 return father[parentId] === rootId;
145 }); 141 });
146 - return treeData != '' ? treeData : data; 142 + return treeData !== '' ? treeData : data;
147 } 143 }
148 144