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

1、ArrayToTree

// 有时候叫fatherId,有时候叫parentId,为了写成通用的,把父节点ID写成一个变量,用的时候直接传进来,ES6支持Object的key为变量
function arrToTree(list, parentKey) {  
  let map = {};
  let tree = [];
  for (let i = 0; i < list.length; i++) {
    map[list[i].id] = list[i];
    list[i].children = [];
  }
  for (let i = 0; i < list.length; i += 1) {
    let node = list[i];
    if (node[parentKey] !== null) {
      map[node[parentKey]].children.push(node);
    } else {
      tree.push(node);
    }
  }
  return tree;
}

2、TreeToArray

//其实就是数据结构中的广度优先遍历
function treeToArrt(tree) {
  let queen = [];
  let out = [];
  queen = queen.concat(tree);
  while(queen.length) {
    let first = queen.shift();
    if (first.children) {
      queen = queen.concat(first.children)
      delete first['children'];
    }
    out.push(first);
  }
  return out;
}

关于作者

zhyim
学海无涯,回头是岸
获得点赞
文章被阅读