1.遍历树的层级关系

1)先整理数据

2)找到id和数据的映射关系

3)然后找到父节点的数据,进行存储

  test() {
const list = [
{ id: "", parentId: "", children: [] },
{ id: "", parentId: "", children: [] },
{ id: "", parentId: "", children: [] },
{ id: "", parentId: "", children: [] },
{ id: "", parentId: "", children: [] }
];
const mapList = [];
const tree = [];
list.forEach(item => { mapList[item.id] = item;
});
list.forEach(item => {
const parentNode = mapList[item.parentId];
if (!parentNode) {
       if (!item.children) {
         item.children = []
       }
          tree.push(item);
} else {
      if (!parentNode.children) {
        parentNode.children = []
      }
          parentNode.children.push(item);
}
});
console.log("tree", tree);
},
05-27 18:08