/** * 树形结构转换 * @param a * @param idStr * @param pidStr * @param chindrenStr * @returns {Array} */ function transData(a, idStr, pidStr, chindrenStr){ let r = [], hash = {}, id = idStr, pid = pidStr, children = chindrenStr, i = 0, j = 0, len = a.length; for(; i < len; i++){ hash[a[i][id]] = a[i]; } for(; j < len; j++){ let aVal = a[j], hashVP = hash[aVal[pid]]; //当前对象&pid对象 if(hashVP){ !hashVP[children] && (hashVP[children] = []); hashVP[children].push(aVal); }else{ r.push(aVal); } } return r; }
/** * 树形结构转换 * @param a * @param idStr * @param pidStr * @returns {Array} */ function transData2Tree(a, idStr, pidStr) { var r = [] var hash = {} var len = a.length for (var i = 0; i < len; i++) { hash[a[i][idStr]] = a[i] } for (var j = 0; j < len; j++) { var aVal = a[j] var hashVP = hash[aVal[pidStr]] if (hashVP) { (!hashVP.children) && (hashVP.children = []) hashVP.children.push(aVal) } else { r.push(aVal) } } return r } /** * 返回一个节点下的所有子孙节点 */ function getChildren(arr, result, pid) { for (var i in result) { if (result[i].pid + '' === pid + '') { arr.push(result[i]._id + '') getChildren(arr, result, result[i]._id) } } return arr }