List 列表转含有children的List
思想:
1、遍历List,生成一个键值对为parentId,children的map;
2、遍历List,为每个对象设置children,过滤掉有父节点的对象
List<Map<String, Object>> mapList = new ArrayList<>();
JSONArray json = JSONArray.parseArray(res);
mapList = JSONArray.toJavaObject(json, List.class);
Map<String,List<Map<String, Object>>> map=new LinkedHashMap<String, List<Map<String, Object>>>();
for (Map<String, Object> obj:mapList) {
String pId=""+obj.get("parentId");
String id=""+obj.get("id");
List<Map<String, Object>> children=map.get(pId);
if(children==null){
children=new LinkedList<Map<String, Object>>();
}
if("3459045988797251584".equals(pId)){//第一层
map.put(id,children);
}else{
children.add(obj);
map.put(pId,children);
}
}
List<Map<String, Object>> list2=new ArrayList<Map<String, Object>>();
for (Map<String, Object> obj:mapList) {
String pId=""+obj.get("parentId");
String id=""+obj.get("id");
obj.put("children",map.get(id));
if(map.get(pId)==null){
list2.add(obj);
}
}
System.out.println(list2);
树形结构遍历
思想:
1、遍历数组中的每一个对象
2、递归遍历每个对象的子节点
function setNodes(nodes,data){
for (var i = 0; i < nodes.length; i++) {
var dataTitle = nodes[i].name;
var obj=Object.assign({},nodes[i]);
nodes[i]={};
nodes[i].title=dataTitle;
nodes[i].expand=true;
nodes[i].children=obj.children;
nodes[i].sysCode=obj.sysCode;
nodes[i].code=obj.code;
if(data){
data.push(nodes[i]);
}
if(nodes[i].children){
setNodes(nodes[i].children,null);
}
}
}
var data=[];
var resdata=[];
setNodes(resdata,data);