js数组扁平数据结构转tree

记录一下日常学习,js数组扁平数据结构转tree

演示数据

const arr = [
  { id: 1, name: '部门1', pid: 0 },
  { id: 2, name: '部门2', pid: 1 },
  { id: 3, name: '部门3', pid: 1 },
  { id: 4, name: '部门4', pid: 3 },
  { id: 5, name: '部门5', pid: 4 },
]

1.map存储 唯一性

function formatDataTree (arr, key, parentKey) {
  const result = [];
  const itemMap = {};
  for (const item of arr) {
    const id = item[key];
    const pid = item[parentKey];

    if (!itemMap[id]) {
      itemMap[id] = {
        children: [],
      }
    }

    itemMap[id] = {
      ...item,
      children: itemMap[id]['children']
    }

    const treeItem = itemMap[id];

    if (pid === 0) {
      result.push(treeItem);
    } else {
      if (!itemMap[pid]) {
        itemMap[pid] = {
          children: [],
        }
      }
      itemMap[pid].children.push(treeItem)
    }

  }
  return result;
}

2.递归

function translateDataToTreeAllTreeMsg (data, parentKey, parentIDKey) {
  let parent = data.filter((value) => Number(value[parentKey]) <= 0);// 父数据
  let children = data.filter((value) => Number(value[parentKey]) > 0);// 子数据
  let translator = (parent, children) => {
    parent.forEach((parent) => {
      parent.children = [];
      children.forEach((current, index) => {
        if (current[parentKey] === parent[parentIDKey]) {
          const temp = JSON.parse(JSON.stringify(children));
          temp.splice(index, 1);
          translator([current], temp);
          typeof parent.children !== "undefined"
            ? parent.children.push(current)
            : (parent.children = [current]);
        }
      });
    });
  };
  translator(parent, children);
  return parent;
}

输出

微信截图_20220808153617.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容