首页 > web前端 > js教程 > 正文

JavaScript 深度嵌套数组子元素的获取方法

心靈之曲
发布: 2025-08-16 19:30:33
原创
639人浏览过

javascript 深度嵌套数组子元素的获取方法

本文介绍了在 JavaScript 中,如何从深度嵌套的数组结构中,根据指定的 ID 获取子元素。通过迭代方法,避免了递归可能带来的栈溢出问题,并提供了详细的代码示例和类型定义,帮助开发者高效地处理复杂的数据结构。针对不同场景,包括指定 ID 和未指定 ID 的情况,给出了相应的解决方案。

从深度嵌套数组中提取指定子元素

在处理具有嵌套结构的 JSON 数据时,经常需要根据某些条件提取特定的子元素。例如,一个表示商品分类的数据结构可能包含多层嵌套的子分类。本文将介绍如何使用 JavaScript 从这种深度嵌套的数组中,根据给定的分类 ID 列表,提取这些 ID 对应的直接子元素。同时,我们还将讨论在没有指定 ID 的情况下,如何返回默认的父子元素列表。

问题分析

核心问题在于如何有效地遍历深度嵌套的数组,并在遍历过程中根据条件筛选出符合要求的元素。传统的递归方法虽然直观,但在数据层级过深时可能会导致调用栈溢出。因此,我们将采用迭代的方式,结合栈的数据结构来解决这个问题。

解决方案:迭代与栈

以下是一种使用迭代和栈来实现该功能的 JavaScript 函数。该函数接受一个分类 ID 数组和一个包含嵌套分类数据的数组作为输入。

百度智能云·曦灵
百度智能云·曦灵

百度旗下的AI数字人平台

百度智能云·曦灵 3
查看详情 百度智能云·曦灵

立即学习Java免费学习笔记(深入)”;

type Category = {
  name: string;
  id: string;
  count: string;
  depth: string;
  children: Category[];
};

const getCategoriesChildren = (
  categoryIds: Category['id'][],
  categories: Category[],
) => {
  const foundChildren: Pick<Category, 'id' | 'count' | 'name'>[] = [];

  if (categoryIds.length === 0) {
    return categories.reduce<Pick<Category, 'id' | 'count' | 'name'>[]>(
      (acc, category) => {
        acc.push(mapCategory(category), ...category.children.map(mapCategory));
        return acc;
      },
      [],
    );
  }

  const stack = [...categories];

  while (stack.length) {
    const category = stack.pop();
    if (!category) continue;
    if (categoryIds.includes(category.id)) {
      foundChildren.push(
        ...category.children.map((childCategory) => ({
          name: childCategory.name,
          id: childCategory.id,
          count: childCategory.count,
        })),
      );
    }
    stack.push(...category.children);
  }

  return foundChildren;
};

const mapCategory = (category: Category): Pick<Category, 'id' | 'count' | 'name'> => ({
    name: category.name,
    id: category.id,
    count: category.count,
})
登录后复制

代码解释:

  1. 类型定义: 首先定义了一个 Category 类型,用于描述分类数据的结构。
  2. getCategoriesChildren 函数:
    • 接受 categoryIds (需要查找的分类 ID 数组) 和 categories (包含嵌套分类数据的数组) 作为参数。
    • 如果 categoryIds 为空,则返回所有顶层分类及其直接子分类,使用 reduce 方法将所有分类数据转化为所需格式。
    • 如果 categoryIds 不为空,则使用栈来迭代遍历嵌套的分类数据。
    • 将顶层分类数据压入栈中。
    • 当栈不为空时,循环执行以下操作:
      • 从栈顶弹出一个分类。
      • 如果该分类的 ID 包含在 categoryIds 中,则将其直接子分类转换为所需格式,并添加到 foundChildren 数组中。
      • 将该分类的子分类压入栈中,以便后续处理。
    • 返回 foundChildren 数组,其中包含所有符合条件的子分类。
  3. mapCategory 函数:
    • 将Category类型的数据转化为Pick<Category, 'id' | 'count' | 'name'>类型的数据

使用示例

const data = [
    {
      name: "Car",
      id: "19",
      count: "20",
      depth: "1",
      children: [
        {
          name: "Wheel",
          id: "22",
          count: "3",
          depth: "2",
          children: [
            {
              name: "Engine",
              id: "101",
              count: "1",
              depth: "3",
              children: [
                {
                  name: "Engine and Brakes",
                  id: "344",
                  count: "1",
                  depth: "4",
                  children: []
                }
              ]
            }
          ]
        }
      ]
    },
    {
      name: "Bike",
      id: "3",
      count: "12",
      depth: "1",
      children: [
        {
          name: "SpeedBike",
          id: "4",
          count: "12",
          depth: "2",
          children: []
        }
      ]
    }
  ];

// 获取 ID 为 '101' 和 '3' 的分类的直接子分类
console.log(getCategoriesChildren(['101', '3'], data));
// 输出:
// [
//   { name: 'Engine and Brakes', id: '344', count: '1' },
//   { name: 'SpeedBike', id: '4', count: '12' }
// ]

// 获取所有顶层分类及其直接子分类
console.log(getCategoriesChildren([], data));
// 输出:
// [
//   { name: 'Car', id: '19', count: '20' },
//   { name: 'Wheel', id: '22', count: '3' },
//   { name: 'Bike', id: '3', count: '12' },
//   { name: 'SpeedBike', id: '4', count: '12' }
// ]
登录后复制

总结

本文介绍了一种使用迭代和栈来处理深度嵌套数组的方法,避免了递归可能带来的栈溢出问题。通过这种方法,我们可以高效地从复杂的数据结构中提取所需的信息。在实际开发中,可以根据具体需求进行适当的调整和优化。

以上就是JavaScript 深度嵌套数组子元素的获取方法的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门推荐
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号