«

js 平面结构转树形结构 tree

emer 发布于 2020-4-7 17:30   1750 次阅读     


var data=[
  { id: 40, parentId: 31, note: "的萨达是" }, 

  { id: 20, parentId: 11, note: "的萨达是" },
  { id: 22, parentId: 20, note: "dsadas" },
  { id: 12, parentId: null, note: "dsadasad萨达s" }, 
  { id: 11, parentId: undefined, note: "dqwds" }, 
  { id: 24, parentId: 22, note: "搜索" },
  { id: 34, parentId: 22, note: "搜索" }
]
function fnSetTreeData(data) {
  var data = [...data];
  var tree = data.filter((father) => {
    var branchArr = data.filter((child) => {
      if (father.id == child.parentId) child._hasParent = true;
      return father.id == child.parentId;

      // MARK 为什么这样写就报错 ? 
      // if (father.id == child.parentId) child._hasParent = true;
      // return child._hasParent
    });
    if (branchArr.length > 0) father.children = branchArr;
    return !father._hasParent;
  });

  // MARK 为什么在这里还得加一个过滤
  tree = tree.filter((item) => {
    return !item._hasParent;
  })
  return tree
}

console.log(fnSetTreeData(arr), null, 2);
-------------------------或者

export function toTree(data) {
  // 删除 所有 children,以防止多次调用
  if(!data) return [];
  data.forEach(function(item) {
    delete item.children;
  });

  // 将数据存储为 以 id 为 KEY 的 map 索引数据列
  var map = {};
  data.forEach(function(item) {
    map[item.id] = item;
  });
  var val = [];
  data.forEach(function(item) {
    // 以当前遍历项,的pid,去map对象中找到索引的id
    var parent = map[item.parentId || item.pid];
    // item.treeId = item.id + '-' + (item.parentId || item.pid)
    // 好绕啊,如果找到索引,那么说明此项不在顶级当中,那么需要把此项添加到,他对应的父级中
    if (parent) {
      (parent.children || (parent.children = [])).push(item);
    } else {
      //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中,作为顶级
      if (item.isOutsider != 1) {
        val.push(item);
      }
    }
  });
  let out = _.filter(data, i => {
    return i.isOutsider == 1;
  });
  if (out) {
    val = val.concat(out);
  }
  return val;
}