如何编写函数从JavaScript深层对象中获取指定节点路径?
Solution: Find Path to Target Node in Nested Object
Got it, let's work through this problem together. We need a function that traverses the nested object structure and returns the full path from the root to the node with the target keyword. This is a classic use case for depth-first search (DFS) since we need to dive into each branch until we find our target, then backtrack to collect the path.
Step-by-Step Implementation (JavaScript)
Here's a recursive function that does exactly what we need:
const findPath = (data, keyword, currentPath = []) => { // Create a new path with the current node's name added const newPath = [...currentPath, data.name]; // Check if current node is the target if (data.name === keyword) { return newPath; } // If there are children, recursively search each one if (data.children) { for (const child of data.children) { const result = findPath(child, keyword, newPath); // Return immediately if we found a match in this branch if (result) { return result; } } } // No match found in this branch return null; }; // Test the function with your sample data const data = { name: "human", children: [ { name: "head", children: [ { name: "eye" } ] }, { name: "body", children: [ { name: "arm" } ] } ] }; const keyword = "eye"; console.log(findPath(data, keyword)); // Output: ["human", "head", "eye"]
How It Works
- Recursive Traversal: We start at the root node, add its name to the current path, then check if it's our target.
- Path Management: We create a copy of the current path each time (
[...currentPath, data.name]) to avoid mutating the path array across recursive calls. - Early Termination: As soon as we find a matching node in any child branch, we return the path immediately—no need to check other branches once we have our result.
- Edge Handling: If a node has no children or none of its children match the keyword, we return
nullto signal this branch doesn't contain the target.
Optional: Collect All Matching Paths
If there could be multiple nodes with the same keyword and you want all paths, you can modify the function to collect results instead of returning on the first match:
const findAllPaths = (data, keyword, currentPath = [], results = []) => { const newPath = [...currentPath, data.name]; if (data.name === keyword) { results.push(newPath); } if (data.children) { for (const child of data.children) { findAllPaths(child, keyword, newPath, results); } } return results; };
内容的提问来源于stack exchange,提问作者Junya Kono
相关产品推荐
相关产品推荐

