js 平面结构转树形结构   tree js 平面结构转树形结构 tree

js 平面结构转树形结构 tree

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);
分享本文至:

评论 0

挤眼 亲亲 咆哮 开心 想想 可怜 糗大了 委屈 哈哈 小声点 右哼哼 左哼哼 疑问 坏笑 赚钱啦 悲伤 耍酷 勾引 厉害 握手 耶 嘻嘻 害羞 鼓掌 馋嘴 抓狂 抱抱 围观 威武 给力
提交评论

清空信息
关闭评论