# Java
public List JsonToTree(List<Map<String, Object>> list){
Map<String,Map> map = new HashMap<>();
for(Map m :list){
map.put(m.get("id")+"", m);
}
List listm = new ArrayList();
for(Map mm :list){
Map ma = map.get(mm.get("pid")+"");
if(ma==null){
listm.add(mm);
continue;
}
List l = new ArrayList();
if(ma.get("children")==null){
l.add(mm);
ma.put("children",l);
}else{
l=(List) (ma.get("children"));
l.add(mm);
ma.put("children",l);
}
}
return listm;
}
# js
function parentson(datas){
var map = {};
//所有的value为key 放入到map
datas.forEach(function (item) {
map[item.value] = item;
});
var val = [];
//添加
datas.forEach(function (item) {
var parent = map[item.pid];
if (parent){
(parent.children || ( parent.children = [] )).push(item);
} else {
val.push(item);
}
});
return val;
};