父级id 对 子级pid 树形数据的转换

166 阅读1分钟
const deplistarr = res.data.filter(item => item.deparmentCode !== 'PLCHP_ROOT_ORG_610000')
res.data
过滤 无用层级

/**
 * id to pid
 * a 对应的是需要树的数据 res.data
 * idStr 为 父级对应的id   id 
 * pidStr 为 子级对应父节点 对应id  pid
 * chindrenStr 为为所要存储的名字   children
 */
export 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;
}