关于javascript:树形结构数据组成树的算法

47次阅读

共计 2060 个字符,预计需要花费 6 分钟才能阅读完成。

[{
  id: 1,
  title: 节点 1,parentId: null
},
{
  id: 2,
  title: 节点 2,parentId: 1
},
{
  id: 3,
  title: 节点 3,parentId: null
},
{
  id: 4,
  title: 节点 4,parentId: 2
},
{
  id: 5,
  title: 节点 5,parentId: 3
}]

形如以上常见后端返回的数据结构。可用以下办法形成树:

getParentData(data) {let cloneData = JSON.parse(JSON.stringify(data));
      let parentData = [];
      for (let parent of cloneData) {if (parent.parentId === null || parent.parentId === "") {
          parent.label = parent.title;
          parent.value = parent.id;
          let childrenCopy = this.getChildren(parent.id, cloneData);
          if (childrenCopy.length > 0) {parent.children = childrenCopy;}
          parentData.push(parent);
        }
      }
      return parentData;
    },
    getChildren(parentId, data) {let children = [];
      for (let child of data) {if (child.parentId === parentId) {
          child.label = child.title;
          child.value = child.id;
          children.push(child);
        }
      }
      for (let child of children) {let childrenCopy = this.getChildren(child.id, data);
        if (childrenCopy.length > 0) {child.children = childrenCopy;}
      }
      return children;
    }

另外,如果须要对某节点后数据做禁用操作。可传入其 ID 值进行筛选。代码如下:

getParentData(data, id){let cloneData = JSON.parse(JSON.stringify(data));
      let parentData = [];
      for(let parent of cloneData){if(parent.parentId === null || parent.parentId === ""){
            parent.label = parent.title;
            parent.value = parent.id;
            if(parent.id === id){parent.disabled = true;}
            else{parent.disabled = false;}
            let childrenCopy = this.getChildren(parent.id, cloneData, id, parent.disabled);
            if(childrenCopy.length > 0){parent.children = childrenCopy;}
            parentData.push(parent);
          }
      }
      return parentData;
    },
    getChildren(parentId, data, id, isDisable){let children = [];
      for(let child of data){if(child.parentId === parentId){
            child.label = child.title;
            child.value = child.id;
            if(isDisable){child.disabled = true;}
            else{if(child.id === id){child.disabled = true;}
              else{child.disabled = false;}
            }
            children.push(child);
          }
      }
      for(let child of children){let childrenCopy = this.getChildren(child.id, data, id, child.isDisable);
          if(childrenCopy.length > 0){child.children = childrenCopy;}
      }
      return children;
    }

针对某个 id,寻找该 ID 在树的门路,可用以下办法遍历寻找:

getTreePath(tree, id) {let path = [];
      function dfs(tree) {for (let i = 0; i < tree.length; i++) {if (tree[i].value === id) {path.unshift(tree[i].value);
            return true;
          } else if (tree[i].children) {if (dfs(tree[i].children)) {path.unshift(tree[i].value);
              return true;
            }
          }
        }
      }
      dfs(tree);
      return path;
    }

正文完
 0