js返回树形结构数据
/** * 树形结构转换 * @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 }
作者:程序员小波与Bug
出处:https://codetrips.cn
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。如有问题,可以邮件:caiya928@aliyun.com
QQ:1419901425 联系我
如果喜欢我的文章,请关注我的公众号:程序员小波与Bug