let arr = [ {"id":111,name:"赵"}, {"id":222,name:"钱"}, {"id":333,name:"孙"}, {"id":444,name:"李"}, {"id":555,name:"周"}, {"id":666,name:"吴"}, ]; let arr2 = []; arr.forEach(function(val, key) { console.log(key); if ( key%3 == 0) { arr2.push(val); } else if(key%3 == 1) { let empty = []; empty.push(val); arr2[parseInt(key/3)].children = empty; } else if(key%3 == 2) { console.log(arr2[parseInt(key/3)].children[0]); arr2[parseInt(key/3)].children[0].children = val; } }); console.log(arr2);
emmm...应该可行
{id:111,name:"赵",pathId:null}
{id:222,name:"钱",pathId:111}
根据你的描述你是将List转换为树,实际上数据结构已经很清晰了,pathId就是该记录的父记录,可能命名为parentId更为合适
private static class Item{
String id;
String name;
String parentId;
List<Item> children=new ArrayList<>();
public Item(String id, String name, String parentId) {
this.id = id;
this.name = name;
this.parentId = parentId;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public List<Item> getChildren() {
return children;
}
public void setChildren(List<Item> children) {
this.children = children;
}
@Override
public String toString() {
return "{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", parentId='" + parentId + '\'' +
", children=" + children +
'}';
}
}
public static void main(String[] args){
Map<String,Item> itemMap= new HashMap<>();
itemMap.put("111",new Item("111","赵",null));
itemMap.put("222",new Item("222","钱","111"));
itemMap.put("333",new Item("333","孙","222"));
itemMap.put("444",new Item("444","李",null));
itemMap.put("555",new Item("555","周","444"));
itemMap.put("666",new Item("666","吴","555"));
List<Item> roots=new ArrayList<>();
for(Item item:itemMap.values()){
if(item.getParentId()==null){
roots.add(item);
}else{
Item parent=itemMap.get(item.getParentId());
if(parent!=null){
parent.getChildren().add(item);
}else{
roots.add(item);
}
}
}
System.out.println(roots);
}
就是个对象数组么,别慌,一成一层往里加
用递归试下
先找到pardId=nan的 这是第一层 然后在拿到底层id递归着找 parid=当前的这个id的