PHP速学视频免费教程(入门到精通)
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
本文档提供了一个 JavaScript教程,用于从嵌套的分类数据结构中提取特定分类ID的所有子项,并将结果扁平化为一个数组。它涵盖了处理不同场景的逻辑,包括指定分类ID和未指定分类ID的情况,并提供了可复用的代码示例。
假设我们有一个嵌套的分类数据结构,每个分类都有 id、name、count 和 children 属性。children 属性是一个包含子分类的数组,子分类也具有相同的结构。我们的目标是编写一个 JavaScript 函数,该函数能够:
我们可以使用递归和栈数据结构来实现这个功能,同时避免使用 for、foreach 和 while 循环。
代码示例(TypeScript)
interface Category { name: string; id: string; count: string; depth: string; children: Category[]; } 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; }; // 示例数据 const data: Category[] = [ { 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); const noCategoryIds = []; const defaultChildren = getCategoriesChildren(noCategoryIds, data); console.log(defaultChildren);
代码解释:
本文提供了一个使用 JavaScript 查找并扁平化特定分类 ID 的子项的教程。通过使用栈数据结构和递归,我们可以避免使用 for、foreach 和 while 循环,从而使代码更加简洁和易于理解。 此方法适用于处理深度嵌套的分类数据,并且可以根据实际需求进行修改。
Java免费学习笔记:立即学习
解锁 Java 大师之旅:从入门到精通的终极指南
已抢21235个
抢已抢3188个
抢已抢3394个
抢已抢5574个
抢已抢5171个
抢已抢35580个
抢