You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用递归.reduce()实现获取指定文件夹的所有父级数组

Fixing Recursive Reduce for Folder Parent Breadcrumbs

Got it, let's sort out this breadcrumb parent collection issue! The problem with your current code is twofold:

  1. When you recursively call getFolderParents(item), you're not merging the result of that recursive call into your accumulator array—you just push the direct parent's name and discard the rest.
  2. There's a type mismatch with parentId in your foldersArray (some are numbers like 1, others are strings like "1.1"), which will break matches if you don't normalize types.

Solution 1: Efficient Map + Recursive Functional Style

First, let's optimize lookups with a Map (avoids looping the entire array every time) and fix the type issue, then use a recursive approach that accumulates the full parent chain:

// Create a map for O(1) folder lookups (run this once, maybe in your component's init)
const folderMap = new Map(this.foldersArray.map(folder => [String(folder.id), folder]));

getFolderParents(folder) {
  // Base case: no parent, return empty array
  if (!folder.parentId) return [];

  // Find the parent folder (normalize parentId to string to match map keys)
  const parent = folderMap.get(String(folder.parentId));
  
  if (!parent) return []; // Handle invalid parentId gracefully

  // Combine the parent's name with the recursive result of its own parents
  return [parent.name, ...this.getFolderParents(parent)];
}

Solution 2: Direct Recursive Reduce (No Map)

If you prefer to skip the map and use reduce directly (less efficient for large arrays, but works for small datasets):

getFolderParents(folder) {
  // Base case: no parent, return empty array
  if (!folder.parentId) return [];

  return this.foldersArray.reduce((acc, item) => {
    // Normalize both IDs to strings to fix type mismatches
    if (String(item.id) === String(folder.parentId)) {
      // Merge the parent's name with the recursive result of its parents
      return [...this.getFolderParents(item), item.name];
    }
    return acc;
  }, []);
}

How It Works

  • Type Normalization: Converting id and parentId to strings ensures we match items correctly, even if your data mixes number and string IDs.
  • Recursive Accumulation: Instead of pushing a single parent name and discarding the recursive call, we spread the result of the recursive call (which is the full chain of the parent's parents) and add the current parent's name to it. This builds the full chain from root to direct parent.

Test It Out

If you call this with the deepest folder:

const targetFolder = this.foldersArray.find(f => f.id === "1.1.1");
console.log(this.getFolderParents(targetFolder)); // Output: ["folder1", "folder1.1"]

This gives you the exact parent chain you need to build your breadcrumb component (e.g., folder1 > folder1.1 > folder1.1.1).

内容的提问来源于stack exchange,提问作者Pierre_T

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:13:05