美文网首页
普通数组转换树形接口

普通数组转换树形接口

作者: 若水亦城空 | 来源:发表于2020-03-23 14:54 被阅读0次

调用方式

 var parentArr = transData(res.data, "id", "pId", "children");

方法函数

/**
 * id to pid
 */
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;
}
```````````````````````

相关文章

网友评论

      本文标题:普通数组转换树形接口

      本文链接:https://www.haomeiwen.com/subject/dfswyhtx.html