首页 > Web开发 > 详细

json转tree

时间:2021-05-13 19:48:18      阅读:14      评论:0      收藏:0      [点我收藏+]
# 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;
};

json转tree

原文:https://www.cnblogs.com/Java93/p/14765710.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!