如何用递归.reduce()实现获取指定文件夹的所有父级数组
Got it, let's sort out this breadcrumb parent collection issue! The problem with your current code is twofold:
- 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. - There's a type mismatch with
parentIdin yourfoldersArray(some are numbers like1, 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
idandparentIdto 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
相关产品推荐
相关产品推荐

