首页 > 编程语言 > 详细

扁平数组和树形结构的相互转换

时间:2022-05-27 23:09:18      阅读:19      评论:0      收藏:0      [点我收藏+]

扁平数组和树形结构的相互转换

扁平数组转换为树形结构(1)

这个是最常用的,当我们从后台获取一个扁平数组的时候,通常比如用idpid来标识父子关系,如:

var arr = [{id: 1, pid: ‘-1‘},{id: 11, pid: ‘1‘},{id: 12, pid: ‘1‘}]

map记录的方法是最常用效果也最好的复杂度是O(nlgn),支持多个根节点:

function listToTree(list) {
    var map = {}, node, tree= [], i;
    for (i = 0; i < list.length; i ++) {
        map[list[i].id] = list[i]; 
        list[i].children = []; 
    }
    for (i = 0; i < list.length; i += 1) {
        node = list[i];
        if (node.pid !== ‘-1‘) {
            map[node.pid].children.push(node);
        } else {
            tree.push(node);
        }
    }
    return tree;
}

listToTree(arr); //[{"id":1,"pid":"-1","children":[{"id":11,"pid":"1","children":[]},{"id":12,"pid":"1","children":[]}]}]

但是项目中有个需求,在后台没有返回给带层级信息level的时候,需要用到层级信息,这样转换没法计算出层级,因此就需要用迭代的方法了,默认根节点层级为0,依次递增:

function listToTreeWithLevel(list, parent, level) {
    var out = []
    for (var node of list) {  
            if (node.pid == parent) {
                node.level = level;
                var children = listToTreeWithLevel(list, node.id, level + 1)
                if (children.length) {
                    node.children = children
                }
                out.push(node)
            }
    }
    return out
}

listToTreeWithLevel(arr, ‘-1‘, 0) //[{"id":1,"pid":"-1","children":[{"id":11,"pid":"1","children":[],"level":1},{"id":12,"pid":"1","children":[],"level":1}],"level":0}]

扁平数组转换为树形结构(2)

fnSetTreeData(list) {
var data = [...list];
data.forEach(father => {
var branchArr = data.filter(child => {
if (father.id == child.parentId) {
child.hasParent = true;
}
return father.id == child.parentId;
});

if (branchArr.length > 0) father.children = branchArr;
});
return data.filter(item => {
return !item.hasParent;
});
}

  

树形结构转换为扁平数组

这个其实就是数据结构中的广度优先遍历:

 
function treeToList(tree) {
  var queen = [];
  var out = [];
  queen = queen.concat(tree);
  while(queen.length) {
      var first = queen.shift();
    if (first.children) {
        queen = queen.concat(first.children)
      delete first[‘children‘];
    }
    
    out.push(first);
  }
  return out;
}

var tree = [{"id":1,"pid":"-1","children":[{"id":11,"pid":"1","children":[]},{"id":12,"pid":"1","children":[]}]}];
treeToList(tree) //[{"id":1,"pid":"-1"},{"id":11,"pid":"1"},{"id":12,"pid":"1"}]

扁平数组和树形结构的相互转换

原文:https://www.cnblogs.com/zhenfeng95/p/15353786.html

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