数据库中数据结构图
封装数据的实体类
@Data
public class MicroCodeDto {
private String id;
private String code;
private String name;
private List<MicroCodeDto> child = new ArrayList<>();
public MicroCodeDto(String id, String code, String name) {
this.id = id;
this.code = code;
this.name = name;
}
}
解析方法
public static Object formatXDMCheckOptions(List<MicroCodeDto> options) {
ArrayList<MicroCodeDto> result = new ArrayList<>();
// 使用map保存所有的字段
HashMap<String, MicroCodeDto> map = new HashMap<>();
options.forEach(bean -> map.put(bean.getCode(), bean));
// 查找并填充父子菜单
options.forEach(bean -> {
// 获取最后一个'.'的index
int index = bean.getCode().lastIndexOf(".");
// 没有'.'说明是顶级菜单
if (index == -1) {
result.add(bean);
} else if (index + 1 < bean.getCode().length()) {
// 子菜单 用最后一个点 分割 找到父菜单code
String newStr = bean.getCode().substring(0, index);
// 找到父菜单
MicroCodeDto fatherDto = map.get(newStr);
// 将所有子菜单 填充到父菜单中
if (!fatherDto.getChild().contains(bean)) {
fatherDto.getChild().add(bean);
}
}
});
return result;
}
返回结果展示