美文网首页
js数组扁平数据结构转tree

js数组扁平数据结构转tree

作者: AnsiMono | 来源:发表于2022-08-08 15:28 被阅读0次

记录一下日常学习,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

相关文章

  • js数组扁平数据结构转tree

    记录一下日常学习,js数组扁平数据结构转tree 演示数据 1.map存储 唯一性 2.递归 输出

  • 扁平数组转tree

    (function init() { let arr = [{ id: 1, ...

  • 扁平数组转tree数组

    1、首先生成扁平数组 2、两种方法 1、递归写法,空间复杂度O(2^n) 2、对象方法,空间复杂度O(n)(一次遍...

  • 扁平数据结构转Tree

    如上一个数据结构,将他转为树形结构。方法一: 解析:遍历两次原数组,并在第一次遍历的时候给数组的每一项添加一个ch...

  • 扁平数据结构转Tree

    在做后台系统和权限的时候经常遇到 扁平化数据转tree 结构 转化前 转化后 最优化性能 主要思路也是先把数据转成...

  • 扁平数据结构转Tree

    自己写的方法,使用递归方式 网上借鉴的方法(该实现的时间复杂度为O(2n)) 网上借鉴的方法(该实现的时间复杂度为...

  • 面试:扁平数据结构转Tree

    题目 扁平的数据结构,转成树。打平的数据内容如下: 输出结果 递归遍历查找 主要思路是提供一个递getChildr...

  • 数据字典,查询到数组转Tree

    Java后台数据字典 字典枚举值 后台查询数据字典集合 //数组转Tree前台js转化

  • 创建树

    将扁平化的节点数组,变成一棵树,使用tree-with-arraynpm i tree-with-array 创建...

  • JS 扁平化(flatten) 数组

    前言 数组是 JS 中使用频率仅次于对象的数据结构,官方提供了众多的 API,今天我们来谈谈如何扁平化(flatt...

网友评论

      本文标题:js数组扁平数据结构转tree

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