使用js实现将有父子关系的数据转换成树形结构数据

1、具有父子关系的一组数据如下,通过id绑定关系

      let arr = [
        {
          id: 1,
          name: "1"
        },
        {
          id: 2,
          name: "1-1",
          parentId: 1
        },
        {
          id: 3,
          name: "1-1-1",
          parentId: 2
        },
        {
          id: 4,
          name: "1-2",
          parentId: 1
        },
        {
          id: 5,
          name: "1-2-2",
          parentId: 4
        },
        {
          id: 6,
          name: "1-1-1-1",
          parentId: 3
        },
        {
          id: 7,
          name: "2"
        }
      ];

2、将最上层没有父级的和子级过滤出来:

      let parents = arr.filter(
        value => value.parentId == "undefined" || value.parentId == null
      );
      let childrens = arr.filter(
        value => value.parentId !== "undefined" && value.parentId != null
      );

 3、双层循环遍历,父级作为最外层:

      let fliterEvent= (parents, childrens) => {
        parents.forEach(parent => {
          childrens.forEach((current, index) => {
            if (current.parentId === parent.id) {
              let temp = JSON.parse(JSON.stringify(children));
              temp.splice(index, 1);
              fliterEvent([current], temp);
              typeof parent.children !== "undefined"
                ? parent.children.push(current)
                : (parent.children = [current]);
            }
          });
        });
      };

4、最终转换事件如下:

  function translator(parents,childrens){
      fliterEvent(parents, childrens);
      return parents;
   }

 

你可能感兴趣的:(JavaScript)