java 将数据转为树形数据

前提

在java中,我们经常需要在前端展示一个树形机构,供用户点击选择,怎么实现呢,js代码

function convertToTreeData(departments, parentId) {
  const tree = [];
  
  departments.forEach(department => {
    if (department.parentId === parentId) {
      const children = convertToTreeData(departments, department.id);
      
      if (children.length > 0) {
        department.children = children;
      }
      
      tree.push(department);
    }
  });
  
  return tree;
}

java后端

和前端代码逻辑一样

public class OrgTreeExp {

    private String id;
    private String label;
    private String parentId;
    private List children;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }

    public String getParentId() {
        return parentId;
    }

    public void setParentId(String parentId) {
        this.parentId = parentId;
    }

    public List getChildren() {
        return children;
    }

    public void setChildren(List children) {
        this.children = children;
    }
}

public static List convertToTreeData(List orgs, String parentId) {
        List tree = new ArrayList<>();

        for (OrgTreeExp org : orgs) {
            if ( org.getParentId().equals(parentId)) {
                List children = convertToTreeData(orgs, org.getId());

                if (!children.isEmpty()) {
                    org.setChildren(children);
                }

                tree.add(org);
            }
        }

        return tree;
    }

如果要调用,直接将参数调用convertToTreeData方法则可,第一次调用传的parentId,必须是顶级节点的父节点

你可能感兴趣的:(java,开发语言,javascript)