首页 新闻 会员 周边

数组的拼装问题,很难

0
[待解决问题]

数组的拼装问题,很难,,,,,,,,,,,,,,,,,,,

海染蓝了天LE的主页 海染蓝了天LE | 初学一级 | 园豆:26
提问于:2018-05-02 16:59
< >
分享
所有回答(5)
1
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...应该可行

mini_fan | 园豆:301 (菜鸟二级) | 2018-05-02 17:29
0

{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);


}

 

 

 

开心朵朵 | 园豆:244 (菜鸟二级) | 2018-05-02 19:46
0

就是个对象数组么,别慌,一成一层往里加

DanBrown | 园豆:1321 (小虾三级) | 2018-05-03 09:44
0

用递归试下

小子贪欢 | 园豆:208 (菜鸟二级) | 2018-05-03 15:50
0

先找到pardId=nan的 这是第一层 然后在拿到底层id递归着找 parid=当前的这个id的 

赵大大 | 园豆:1 (初学一级) | 2018-05-04 09:24
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册