一维数组转为树形结构数组

831 阅读1分钟

I. 一维数组转换为树形结构数组

通过递归和数组方法最简单实现

思路:

  1. 确定循环体
  2. 通过filter找到目标
  3. 通过map确定循环体并且循环目标

示例:

const arrData = [{
  id: 1,
  parentId: null
}, {
  id: 2,
  parentId: 1
}, {
  id: 3,
  parentId: 1
}, {
  id: 4,
  parentId: 2
}, {
  id: 5,
  parentId: 4
}];

const nest = (items, id = null, link = 'parentId') =>
  items
  .filter(item => item[link] === id)
  .map(item => ({
    ...item,
    children: nest(items, item.id)
  }));

console.log(nest(arrData))

引入hash,时间复杂度最低的方式实现一维数组转tree

时间复杂度为O(n)

var arrayToTree = (arr, rootId) => {
  const map = {};
  for (const iterator of arr) {
    map[iterator['id']] = iterator;
  }
  for (const iterator of arr) {
    const key = iterator['pid'];
    if (!(key in map)) continue;
    map[key].children = (map[key].children || []).concat(iterator);
  }
  return map[rootId];
};

II. 树形结构数组转化为一维数组

  const treeToArray = (treeData, outputData = []) => {
   treeData.reduce((total, current)=> {
        if(current.children && current.children.length > 0) {
          treeToArray(current.children, outputData)
        }
        delete current.children
        total.push(current)
        return total
    }, outputData)
}