Javascript —— 线转树 or 树转线

线树互转:

const array2tree = (list,key,extendKey)=>{
    var map={};
    list.forEach((item)=>{
        if(!map[item[key]]){
            map[item[key]]=item;
        }
    });
    list.forEach((item)=>{
        if(!!item[extendKey]){
            map[item[extendKey]].children ? map[item[extendKey]].children.push(item) : map[item[extendKey]].children=[item];
        }
    });
    return list.filter(function(item){
        if(!item[extendKey]){
            return item;
        } 
    });
},
tree2array = (list, key) => {
  return list.reduce((con, item) => {
             var callee = arguments.callee;
             con.push(item);
             if (item[key] && item[key].length >0)
               item[key].reduce(callee, con);
                 return con;
             }, []).map(function(item){
             item[key] = [];
             return item;
           })
}

  

posted @ 2021-08-13 16:41  叶落深秋  阅读(71)  评论(0编辑  收藏  举报