javascript封装树数据处理插件treejs

本文介绍了一款名为TREEJS的JavaScript插件,用于处理复杂的树结构数据,包括创建、增删改查等操作。代码简洁易用,已上传至Gitee,适用于处理项目中的树形数据需求。示例代码展示了如何使用该插件进行各种操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 我们在做项目的时候经常会遇到管誉组织、部分、分类、等树结构的数据,在数据结构里面算是复杂类型的数据,处理起来会有点麻烦,一般都会使用到递归,最近自己在做项目的时候页遇到类似的需求,于是自己花了点时间封装了一个专门处理树数据的小插件,里面集成了一些常见的树处理方法,可以直接调用使用。代码不到300行,小巧易用,由于本人水平有限,可能写的不是很好,或者有些小bug,欢迎各位在使用过程中遇到问题指正错误,或者有更好的想法都可以留言交流。代码已经上传到gitee上了,有时间或者新的功能我会更新上去。欢迎下载使用。

TREEJS专门用于处理树数据的插件,包含创建树、新增节点、修改节点、删除节点、查询节点、获取节点层级等常见功能,插件小巧易用。

调用:

const OBJ = new $TREE('pid', 'children', 'name', 0);
    let tree = OBJ.create(db);
    console.log('树数据==', tree);
    console.log('tree数据==', OBJ.sortTreeNodeChildrenByKey(tree, 2, 'name'));

    let parentNode = OBJ.getParentNode(tree, 5);
    console.log('父节点node==', parentNode);

    let node = OBJ.getTreeNodeById(tree, 5);
    console.log('节点node==', node);

    let level = OBJ.getLevelNode(tree, 5);
    console.log('层级节点node==', level);

    OBJ.setTreeNodeValue(tree, 5, 'zyc', [1, 2, 3, 4]);
    console.log('设置节点node==', tree);

    let value = OBJ.getTreeNodeValueByKey(tree, 5, 'zyc');
    console.log('获取节点node-value==', value);

    OBJ.delTreeNodeKey(tree, 5, 'zyc');
    console.log('删除key的树节点数据==', tree);

    OBJ.appendChildrenNode(tree, 5, {id: 3232, pid: 21, name: '新增子节点1'});
    OBJ.appendChildrenNode(tree, 5, {id: 4324, pid: 21, name: '新增子节点2'});
    console.log('删除key的树节点数据==', tree);

    OBJ.clearChildrenNode(tree, 5);
    console.log('清空树子节点数据==', tree);

    let nodeLevel = OBJ.getNodeLevel(tree, 5);
    console.log('树节点层级==', nodeLevel);

    let childrens = OBJ.getParentNodes(tree, 5);
    console.log('树节子子节点==', childrens);

运行结果如下:

下载地址: csdn下载地址

码云地址:treejs

源码如下:

((w) => {
  let $TREE = w.$TREE;
  if (!w.$TREE) {
    w.$TREE = {};
  }
  // 排序函数
  function objSortBykey(objArr, key) {
    let result = objArr.slice(0);
    return result.sort((a, b) => a[key] - b[key]);
  }
  function TREEOBJ (pidKey, childrenKey, label, topPid) {
    // 对象主体
    this.pidKey = pidKey; // 所属父节点id key
    this.topPid = topPid; // 顶级父节点id
    this.childrenKey = childrenKey; // 子节点children
    this.label = label; // 节点labe 的key值

    // data 传进的树数据列表 pidKey 所属父级id对应的key值
    this.create = function (data, pidKey = this.pidKey, pid) {
      pid = pid || this.topPid; // 0为最高父级节点父id
      let list = [];
      data.map(item => {
        if (item[pidKey] == pid) {
          item[childrenKey] = this.create(data, pidKey, item.id);
          list.push(item);
        }
      });
      return list;
    };

    // 将树型结构数据处理成二位数组返回
    this.getTreeDataList = function (data) {
      const res = [];
      function getData(data) {
        data.forEach(v => {
          res.push(v);
          if (v[childrenKey]) {
            getData(v[childrenKey]);
          }
        });
      }
      getData(data);
      return res;
    };

    // 获取树节点的数量
    this.getTreeNodeCount = function (data) {
      return this.getTreeDataList(data).length || null;
    };

    // 根据对树节点的子节点根据key值进行排序
    this.sortTreeNodeChildrenByKey = function (data, id, key) {
      this.getTreeItem(data, id, item => {
        if (item) {
          item[childrenKey] = objSortBykey(item[childrenKey], key);
        }
      });
      return data;
    };

    // id获取节点递归函数
    this.getTreeItem = function (data, id, callBack) {
      data.map(item => {
        if (item.id == id) {
          callBack && (typeof callBack == 'function') && callBack(item);
        } else {
          if (item[childrenKey]) {
            this.getTreeItem(item[childrenKey], id, callBack);
          }
        }
      });
    };

    // 根绝树节点id获取树节点的值
    this.getTreeNodeById = function (data, id) {
      let result = null; // 运行结果
      this.getTreeItem(data, id, item => {
        result = item;
      });
      return result;
    };

    // 设置修改树中的key对象值
    this.setTreeNodeValue = function (data, id, key, value) {
      this.getTreeItem(data, id, item => {
        item[key] = value;
      });
    };

    // 根据id获取对应树中的key值
    this.getTreeNodeValueByKey = function (data, id, key) {
      let value = null;
      this.getTreeItem(data, id, item => {
        value = item[key];
      });
      return value;
    };

    // 根据id删除对应树中的key值
    this.delTreeNodeKey = function (data, id, key) {
      let value = null;
      this.getTreeItem(data, id, item => {
        value = item[key];
        if (key in item) {
          delete item[key];
        }
      });
      return value;
    };

    // 往树里面追加子节点
    this.appendChildrenNode = function (data, id, node = {}) {
      this.getTreeItem(data, id, item => {
        if (item) {
          if (item[childrenKey]) {
            item[childrenKey].push(node);
          } else {
            item[childrenKey] = [];
            item[childrenKey].push(node);
          }
        }
      });
      return data;
    };

    // 根据id 清空子节点
    this.clearChildrenNode = function (data, id) {
      this.getTreeItem(data, id, item => {
        if (item) {
          item[childrenKey] = [];
        }
      });
    };

    // 通过子节点id删除子节点
    this.delChildrenNodeById = function (data, id, childId) {
      this.getTreeItem(data, id, item => {
        if (item) {
          (item[childrenKey] || []).forEach((v, idx) => {
            if (v.id == childId) {
              item[childrenKey].splice(idx, 1);
            }
          });
        }
      });
    };

    // 获取父级节点
    this.getParentNode = function (data, id) {
      let currentNode = null;
      let parentNode = null;

      this.getTreeItem(data, id, item => {
        if (item) {
          currentNode = item;
        }
      });

      if (currentNode) {
        this.getTreeItem(data, currentNode[this.pidKey], item => {
          if (item) {
            parentNode = item;
          }
        });
      }

      return parentNode;
    };

    // 获取父级及祖先节点
    this.getParentNodes = function (data, id) {
      let parentNodes = this.getLevelNode(data, id);
      return parentNodes;
    };

    // 获取子节点及子孙所有节点
    this.getChildrenNodes = function (data, id) {
      let res = [];
      let childrens = [];
      this.getTreeItem(data, id, item => {
        if (item) {
          childrens = item[childrenKey];
        }
      });
      function getChs (data) {
        for (let i = 0, len = data.length; i < len; i++) {
          res.push(data[i]);
          if (data[i][childrenKey] && data[i][childrenKey].length > 0) {
            getChs(data[i][childrenKey]);
          }
        }
      }
      getChs(childrens);
      return res;
    };

    // 获取子节点及子节点
    this.getChildrenNode = function (data, id) {
      let childrens = [];
      this.getTreeItem(data, id, item => {
        if (item) {
          childrens = item[childrenKey];
        }
      });
      return childrens;
    };

    // 辅组查询层级递归遍历函数
    this.getTreeLevelNode = function (data, id, topPid = this.topPid, result, pidKey = this.pidKey) {
      let currentId = id;
      let node = this.getTreeNodeById(data, currentId);
      result.push(node);
      if (node && node[pidKey] && node[pidKey] !== topPid) {
        this.getTreeLevelNode(data, node[pidKey], topPid, result, pidKey);
      }
    };

    // 根据id获取当前树节点的层级节点数据(倒序), topPid 最顶级父节点id
    this.getLevelNode = function (data, id, topPid = this.topPid, pidKey = this.pidKey) {
      let result = [];
      this.getTreeLevelNode(data, id, topPid, result, pidKey);
      return result || [];
    };

    // 获取当前节点层级
    this.getNodeLevel = function (data, id) {
      const res = this.getLevelNode(data, id);
      return res.length || 0;
    };
    
  }

  w.$TREE = TREEOBJ;
})(window);

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值