Array to Tree & Tree to Array

721 阅读1分钟

数组与树结构互转

  • 数组转树
  • 树转数组

测试数据

const data = [{
  "id": "12",
  "parentId": "0",
  "text": "Man",
  "level": "1",
  "children": null
}]

数组转树

常见于前后端数据交互
思路:
数组转树就是将数据通过关联属性重新排布的问题,因此得到两个关键信息

  • (记录下标)需要操控数组,就需要用到数组下标
  • (记录属性)需要重排结构,就需要用到属性关系

因此可以通过一个map结构管控两个关键信息,使得可以通过 id 查找到指定位置

const listToTree = (list) => {
  const roots = [];
  const map = {};
  for(let i in list) {
    map[list[i].id] = i;
    list[i].children = [];
  }
  for(let i in list) {
    const node = list[i]
    if(node.parentId === '0') {
      roots.push(node)
    } else {
      list[map[node.parentId]].children.push(node);
    }
  }
  return roots;
}

树转数组

常见于前后端数据交互
思路:
从顶节点开始,下探遍历,遇到 children 就拿出来

  • 构建一个结果数组,遍历源数据,遇到无 children 的节点就丢进结果数组里面
  • 遍历的时候可以直接对源数据拷贝实现增删
const treeToArray = (tree) => {
  const _tree = [...tree];
  const r = [];
  while(_tree.length) {
    const _f = _tree.shift();
    if(_f.children) {
      _tree.push(..._f.children);
      delete _f.children;
    }
    r.push(_f);
  }
  return r;
}