通过list数组获得 树形图的数组

169 阅读1分钟
 function transData(a, idStr, pidStr, chindrenStr) {
                        var 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++) {
                            var aVal = a[j], hashVP = hash[aVal[pid]];
                            if (hashVP) {
                                !hashVP[children] && (hashVP[children] = []);
                                hashVP[children].push(aVal);
                            } else {
                                r.push(aVal);
                            }
                        }
                        return r;}
           
           

调用方法:let root = transData(a, idStr, pidStr, chindrenStr)

a:后台数据

idStr:数组对象中的每一条对象的唯一标识ID

pidStr:每条数据的关系字段(所属层级字段)

chindrenStr:最后生成的树状结构中的子对象的键名

示例

this.groupData = this.transData(arr, "id", "pid", "children");