扁平数据结构和树结构之间的转化

333 阅读5分钟

一: 扁平数据转树形数据结构需要数据里每一项拥有id和pid,用于确定父子关系,如下

const data = [
  {id:"01", name: "张大大", pid:"", job: "项目经理"},
    
  {id:"02", name: "小亮", pid:"01", job: "产品leader"},
  {id:"07", name: "小丽", pid:"02", job: "产品经理"},
  {id:"08", name: "大光", pid:"02", job: "产品经理"},
    
  {id:"03", name: "小美", pid:"01", job: "UIleader"},
  {id:"09", name: "小高", pid:"03", job: "UI设计师"},
  {id:"05", name: "老王", pid:"01", job: "测试leader"},
  {id:"06", name: "老李", pid:"01", job: "运维leader"},
    
  {id:"04", name: "老马", pid:"01", job: "技术leader"},
  {id:"10", name: "小刘", pid:"04", job: "前端工程师"},
  {id:"11", name: "小华", pid:"04", job: "后端工程师"},
  {id:"12", name: "小李", pid:"04", job: "后端工程师"},
    
  {id:"13", name: "小赵", pid:"05", job: "测试工程师"},
  {id:"14", name: "小强", pid:"05", job: "测试工程师"},
  {id:"15", name: "小涛", pid:"06", job: "运维工程师"}
]

方法一:遍历过滤

方法简述,1.定义空数组,2.遍历找爹,pid为''是最大的爹3.把最大的放进数组4.过滤所有数组,pid和爹的id相等的形成新数组,设置成爹的属性5.返回刚才定义的数组6.打印查看

function arrTotree(list) {
            const treeArr = []
            list.forEach(item => {
                if (item.pid === '') {
                    treeArr.push(item)
                }
                const children = list.filter(obj => obj.pid === item.id)
                if (children.length === 0) return
                item.children = children
            })
            return treeArr
        }
        const arr = arrTotree(data)
        console.log(arr);

方法二:递归遍历数组

方式1:

function arrTotree(list, rootValue) {
            const treeArr = []
            list.forEach(item => {
                if (item.pid === rootValue) {
                    const children = arrTotree(list, item.id)
                    if (children.length) {
                        item.children = children
                    }
                    treeArr.push(item)
                }
            })
            return treeArr
        }
        const arr = arrTotree(data, '')
        console.log(arr);

方式2:

function convertToTree(list, parentId = null) {
    const children = list.filter(node => node.parentId === parentId);
    if (!children.length) {
        return null;
    }
    return children.map(node => ({
        ...node,
        children: convertToTree(list, node.id)
    }));
}

const treeData = convertToTree(list);
console.log(treeData);

该算法的流程为:

  • 使用 filter() 函数过滤出所有的子节点。
  • 使用 map() 函数构造每个子节点的新结构,并使用递归来处理子节点的 children 属性。

方法三:

不用递归,也能搞定

主要思路是先把数据转成Map去存储,之后遍历的同时借助对象的引用,直接从Map找对应的数据做存储

function arrayToTree(items) {
  const result = [];   // 存放结果集
  const itemMap = {};  // 
    
  // 先转成map存储
  for (const item of items) {
    itemMap[item.id] = {...item, children: []}
  }
  
  for (const item of items) {
    const id = item.id;
    const pid = item.pid;
    const treeItem =  itemMap[id];
    if (pid === 0) {
      result.push(treeItem);
    } else {
      if (!itemMap[pid]) {
        itemMap[pid] = {
          children: [],
        }
      }
      itemMap[pid].children.push(treeItem)
    }

  }
  return result;
}

从上面的代码我们分析,有两次循环,该实现的时间复杂度为O(2n),需要一个Map把数据存储起来,空间复杂度O(n) 最优性能:主要思路也是先把数据转成Map去存储,之后遍历的同时借助对象的引用,直接从Map找对应的数据做存储。不同点在遍历的时候即做Map存储,有找对应关系。性能会更好。

function arrayToTree(items) {
  const result = [];   // 存放结果集
  const itemMap = {};  // 
  for (const item of items) {
    const id = item.id;
    const pid = item.pid;

    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;
}

方法四:

还有一些第三方库可以帮助你转换扁平数据为树形结构,例如 lodash 中的 _.groupBy() 和 _.mapValues() 方法可以帮助你将扁平数据转换为树形数据。

const flatData = [
    { id: 1, name: 'Node 1', parentId: null },
    { id: 2, name: 'Node 2', parentId: null },
    { id: 3, name: 'Node 3', parentId: 1 },
    { id: 4, name: 'Node 4', parentId: 2 },
    { id: 5, name: 'Node 5', parentId: 2 }
];

const tree = _(flatData)
    .groupBy('parentId')
    .mapValues((children, parentId) => ({
        id: parentId || 'root',
        children: children.map(({ id, name, parentId }) => ({ id, name, parentId }))
    }))
    .values()
    .value();

console.log(tree)

在这种情况下,假设parentId为null的数据项是根节点,那么所有其它的数据项的 parentId 分别对应它的父节点,我们可以使用 groupBy() 来将所有节点根据它们的 parentId 分组,然后我们可以使用 mapValues() 来构造每个组的新结构。 二: 树结构转化为扁平结构 方法一:递归

const treeData = [{
    id: 1,
    name: 'Node 1',
    children: [
        { id: 2, name: 'Node 2', children: [{ id: 3, name: 'Node 3' }, { id: 4, name: 'Node 4' }] },
        { id: 5, name: 'Node 5' }
    ]
}];

function convertToFlat(data, parentId = null) {
    return data.reduce((acc, curr) => {
        acc.push({ ...curr, parentId });
        if (curr.children) {
            acc = acc.concat(convertToFlat(curr.children, curr.id));
        }
        return acc;
    }, []);
}

const flatData = convertToFlat(treeData);
console.log(flatData);

该算法的流程为:

  • 使用 reduce() 函数遍历每个节点,并将父节点的 id 作为参数传递给递归函数。
  • 使用 push() 函数将当前节点添加到结果数组中。
  • 使用 concat() 函数将递归调用的结果与结果数组连接在一起。
  • 如果当前节点有 children 属性,则递归调用 convertToFlat() 函数,并将当前节点的 id 作为父节点传递给函数。

注意:该方法返回的扁平结构数据未将 children属性删除,因此存在冗余的数据。

这是一种将树形结构数据转换为扁平数组的方法,如果有其他特定的需求,还可以使用其他方法来转换数据,例如使用广度优先遍历算法,使用队列存储节点。

方法二:

const treeData = [
    {
        id: 1,
        name: 'Node 1',
        children: [
            {
                id: 2,
                name: 'Node 2',
                children: [
                    { id: 3, name: 'Node 3' },
                    { id: 4, name: 'Node 4' },
                ]
            },
            { id: 5, name: 'Node 5' },
        ]
    },
    {
        id: 6,
        name: 'Node 6',
        children: [
            { id: 7, name: 'Node 7' }
        ]
    },
];

function convertToFlat(treeData, parentId = null) {
    let flatData = [];
    for (let node of treeData) {
        flatData.push({ id: node.id, name: node.name, parentId });
        if (node.children) {
            flatData = flatData.concat(convertToFlat(node.children, node.id));
        }
    }
    return flatData;
}

const flatData = convertToFlat(treeData);
console.log(flatData);

该算法的流程为:

  • 创建一个空的扁平数组。

  • 递归遍历树形数组中的每个节点,将当前节点添加到扁平数组中。

  • 对于当前节点的子节点,继续使用递归,并将子节点添加到扁平数组中。

  • 返回扁平数组

注意:该方法需要手动构造push 到扁平数组的对象,通用性较差。 方法三:

let data = [{
    id: 1, pid: 0, name: '沃尔玛', childrens: [
        {
            id: 2, pid: 1, name: '生鲜区', childrens: [
                { id: 4, pid: 2, name: '鱼' },
                { id: 5, pid: 2, name: '牛肉' }
            ]
        },
        {
            id: 3, pid: 1, name: '日用品区', childrens: [
                { id: 6, pid: 3, name: '卫生纸' },
                { id: 7, pid: 3, name: '牙刷' }
            ]
        }
    ]
}];

function convertToFlat(treeData) {
    let flatData = [];
    for (let i = 0; i < treeData.length; i++) {
        if (treeData[i].childrens) {
            flatData.push(...convertToFlat(treeData[i].childrens));
            delete treeData[i].childrens;
        }
        flatData.push({ ...treeData[i] });
    }
    return flatData;
}

let flatData = convertToFlat(data);
console.log(flatData);

该方法通用性较强,对树形结构数组数据内部具体的属性名 要求较小(除 childrens)。