当前位置:首页 > JavaScript

js实现树形

2026-01-31 22:58:51JavaScript

js实现树形结构的方法

递归法

递归是构建树形结构的常见方法。通过递归函数可以遍历嵌套的数据结构,生成树形视图。

function buildTree(data, parentId = null) {
  const tree = [];
  data.forEach(item => {
    if (item.parentId === parentId) {
      const children = buildTree(data, item.id);
      if (children.length > 0) {
        item.children = children;
      }
      tree.push(item);
    }
  });
  return tree;
}

非递归法

使用对象映射可以提高性能,特别适合大数据量的树形结构构建。

function buildTreeWithMap(data) {
  const map = {};
  const tree = [];

  data.forEach(item => {
    map[item.id] = { ...item, children: [] };
  });

  data.forEach(item => {
    if (item.parentId && map[item.parentId]) {
      map[item.parentId].children.push(map[item.id]);
    } else {
      tree.push(map[item.id]);
    }
  });

  return tree;
}

使用第三方库

一些成熟的库如lodashd3-hierarchy等提供了树形结构处理的工具函数。

js实现树形

import { groupBy, mapValues } from 'lodash';

function buildTreeWithLodash(data) {
  const grouped = groupBy(data, 'parentId');
  const tree = mapValues(grouped, items => 
    items.map(item => ({
      ...item,
      children: grouped[item.id] || []
    }))
  );
  return tree[null] || [];
}

树形结构的渲染方法

递归组件

在Vue/React等框架中可以使用递归组件渲染树形结构。

function TreeNode({ node }) {
  return (
    <li>
      {node.name}
      {node.children && (
        <ul>
          {node.children.map(child => (
            <TreeNode key={child.id} node={child} />
          ))}
        </ul>
      )}
    </li>
  );
}

虚拟滚动优化

对于大型树形结构,虚拟滚动可以提高性能。

js实现树形

import { FixedSizeTree } from 'react-vtree';

function Tree({ treeData }) {
  const treeWalker = function* () {
    for (let node of treeData) {
      yield {
        id: node.id,
        data: node,
        isOpen: true,
        nestingLevel: 0
      };
    }
  };

  return (
    <FixedSizeTree
      treeWalker={treeWalker}
      itemSize={30}
      height={500}
      width={300}
    />
  );
}

树形结构的操作

添加节点

function addNode(tree, newNode, parentId) {
  if (tree.id === parentId) {
    tree.children = tree.children || [];
    tree.children.push(newNode);
    return true;
  }

  if (tree.children) {
    for (let child of tree.children) {
      if (addNode(child, newNode, parentId)) {
        return true;
      }
    }
  }

  return false;
}

删除节点

function removeNode(tree, nodeId) {
  if (tree.children) {
    tree.children = tree.children.filter(child => child.id !== nodeId);
    for (let child of tree.children) {
      removeNode(child, nodeId);
    }
  }
}

查找节点

function findNode(tree, nodeId) {
  if (tree.id === nodeId) {
    return tree;
  }

  if (tree.children) {
    for (let child of tree.children) {
      const found = findNode(child, nodeId);
      if (found) return found;
    }
  }

  return null;
}

性能优化建议

使用对象映射替代递归查找可以提高性能。对于静态树形结构,可以考虑预计算路径或层级关系。

大型树形结构应考虑分页加载或虚拟滚动技术。避免直接操作DOM,使用框架的响应式机制更新视图。

Immutable数据结构有助于优化渲染性能,特别是在React等框架中。

标签: js
分享给朋友:

相关文章

js实现继承

js实现继承

原型链继承 通过将子类的原型指向父类的实例实现继承。子类实例可以访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Parent…

js 进度条的实现

js 进度条的实现

使用 HTML 和 CSS 创建基础进度条 HTML 结构可以简单使用一个 div 元素作为容器,内部嵌套另一个 div 表示进度: <div class="progress-containe…

js实现pdf在线预览

js实现pdf在线预览

使用PDF.js实现PDF在线预览 PDF.js是由Mozilla开发的一个开源JavaScript库,可以在网页中直接渲染PDF文件。以下是实现PDF在线预览的步骤: 引入PDF.js库 在HT…

js jquery

js jquery

jQuery 简介 jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画设计和 Ajax 交互。它兼容多种浏览器,提供易于使用的 API,使开发者能够…

js实现祖玛

js实现祖玛

实现祖玛游戏的核心思路 祖玛游戏的核心玩法是发射彩色珠子,形成三个或以上相同颜色的珠子即可消除。以下是使用JavaScript实现的基本框架。 游戏初始化 创建画布并初始化游戏状态: const…

js手势实现

js手势实现

手势识别实现方法 在JavaScript中实现手势识别通常涉及监听触摸事件(touchstart、touchmove、touchend)或鼠标事件(mousedown、mousemove、mouseu…