关于前端:将一维数据转化成tree

题目:
将一维数组,转化成嵌套的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));

也能够用递归的形式写,等我钻研分明了再补充

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理