#yyds干货盘点#将一维数据转化成tree

阅读 52

2023-03-30

将一维数组,转化成嵌套的tree

const arr = [
    { id: 1, title: "child1", parentId: 0 },
    { id: 2, title: "child2", parentId: 0 },
    { id: 3, title: "child1_1", parentId: 1 },
    { id: 4, title: "child1_2", parentId: 1 },
    { id: 5, title: "child2_1", parentId: 2 }
  ]

const buildChildrenArr = (arr) => {
    const res = [];
    const map = {};
    for ( let i = 0; i < arr.length; i++) {
      map[arr[i].id] = { ...arr[i], children: []};
      const key = arr[i].id;
      if (!map[key].parentId) {
        res.push(map[key])
      } else {
        const parentId = map[key].parentId
        if (parentId === map[parentId].id) {
          map[parentId].children.push(map[key])
        }
      }
    }
    return res;
  };

  console.log('buildChildrenArr', buildChildrenArr(arr));

也可以用递归的方式写

function buildTree(arr, parentId) {
    const result = [];
    for (let i = 0; i < arr.length; i++) {
      const item = arr[i];
      if (item.parentId === parentId) {
        const children = buildTree(arr, item.id);
        if (children.length > 0) {
          item.children = children;
        }
        result.push(item);
      }
    }
    return result;
  }
  
  
  const tree = buildTree(arr, 0);

精彩评论(0)

0 0 举报