从嵌套数据中提取指定分类ID的子项并扁平化:JavaScript 教程

从嵌套数据中提取指定分类ID的子项并扁平化:JavaScript 教程

本文档提供了一个 JavaScript 教程,用于从深度嵌套的分类数据中提取特定分类 ID 的所有子项,并将结果扁平化为一个数组。该方法避免了使用 forforeachwhile 循环,而是采用结构和 map 等函数式编程技巧,提供了一种高效且可读性强的解决方案。同时,处理了未传递分类 ID 和传递的 ID 无子项等情况。

本文将介绍如何使用 JavaScript 从一个深度嵌套的分类数据结构中,根据给定的分类 ID 列表,提取这些 ID 对应的所有子项,并将结果扁平化为一个一维数组。我们将避免使用传统的 for、foreach 和 while 循环,而是采用更现代的函数式编程方法,提高代码的可读性和可维护性。

数据结构

首先,我们定义一个分类数据结构 Category,它包含 name、id、count 和 children 属性。children 属性是一个 Category 类型的数组,表示该分类的子分类。

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

例如:

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: []         }       ]     }   ];

实现方法

我们的目标是编写一个函数 getCategoriesChildren,它接收一个分类 ID 数组 categoryIds 和一个分类数据数组 categories 作为输入,并返回一个包含所有指定分类 ID 的子项的扁平化数组。

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

该函数的核心思路是使用栈来模拟深度优先搜索(DFS)。我们将初始的分类数据压入栈中,然后不断从栈中弹出元素,并检查该元素是否是目标分类的子项。如果是,则将其子项也压入栈中,继续搜索。

为了避免使用 for、foreach 和 while 循环,我们将使用 map 等函数式编程技巧来处理数组。

const mapCategory = (category: Category) => ({   name: category.name,   id: category.id,   count: category.count, });  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: (Category & { isDesired?: boolean })[] = [...categories];    while (stack.length) {     const category = stack.pop();     if (!category) continue;      const isDesiredCategory =       categoryIds.includes(category.id) || category.isDesired;      if (isDesiredCategory) {       foundChildren.push(...category.children.map(mapCategory));     }      stack.push(       ...(isDesiredCategory         ? category.children.map((child) => ({ ...child, isDesired: true }))         : category.children),     );   }    return foundChildren; };

代码解释:

  1. mapCategory 函数: 该函数用于从 Category 对象中提取 name、id 和 count 属性,创建一个新的对象。这是为了确保返回的子项数组只包含我们需要的属性。

  2. getCategoriesChildren 函数:

    • 参数: 接收一个分类 ID 数组 categoryIds 和一个分类数据数组 categories 作为输入。
    • foundChildren 数组: 用于存储找到的子项。
    • 处理 categoryIds 为空的情况: 如果 categoryIds 为空,则返回所有父分类和直接子分类。这里使用了 reduce 方法将 categories 数组转换为一个包含父分类和直接子分类的扁平化数组。
    • 初始化栈: 创建一个栈 stack,并将 categories 数组中的所有元素压入栈中。 每个元素除了 Category 属性外,还包含一个 isDesired 属性,用于标记该分类是否是目标分类的子项。
    • 循环处理栈中的元素:
      • 从栈中弹出一个元素 category。
      • 判断该元素是否是目标分类的子项:如果 categoryIds 包含该元素的 id,或者该元素的 isDesired 属性为 true,则认为该元素是目标分类的子项。
      • 如果该元素是目标分类的子项,则将其子项添加到 foundChildren 数组中。
      • 将该元素的子项压入栈中。如果该元素是目标分类的子项,则将其子项的 isDesired 属性设置为 true。
    • 返回结果: 返回 foundChildren 数组。

使用示例

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: []         }       ]     }   ];  const categoryIds = ['22', '3']; const children = getCategoriesChildren(categoryIds, data); console.log(children); // Expected Output: // [ //   { name: 'Engine', id: '101', count: '1' }, //   { name: 'Engine and Brakes', id: '344', count: '1' }, //   { name: 'SpeedBike', id: '4', count: '12' } // ]  const noCategoryIds = []; const parentAndChildren = getCategoriesChildren(noCategoryIds, data); console.log(parentAndChildren); // Expected Output: // [ //   { name: 'Car', id: '19', count: '20' }, //   { name: 'Wheel', id: '22', count: '3' }, //   { name: 'Bike', id: '3', count: '12' }, //   { name: 'SpeedBike', id: '4', count: '12' } // ]  const emptyCategoryIds = ['999']; const emptyChildren = getCategoriesChildren(emptyCategoryIds, data); console.log(emptyChildren); // Expected Output: // []

总结

本文介绍了一种使用 JavaScript 从深度嵌套的分类数据结构中提取指定分类 ID 的所有子项,并将结果扁平化为一个数组的方法。该方法避免了使用传统的 for、foreach 和 while 循环,而是采用栈结构和 map 等函数式编程技巧,提供了一种高效且可读性强的解决方案。该方法可以应用于各种需要处理嵌套数据结构的场景,例如:网站导航、商品分类、组织结构等。

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享