JavaScript递归函数处理嵌套对象:生成层级键路径数组的实现问询
Fixing Nested Object Path Traversal for Target Entries
Let's break down how to solve this recursive traversal problem so you can get those full dotted paths to every { "=": value } entry.
What's Missing in Your Current Code?
Your current approach doesn't pass the accumulated path prefix to the recursive call—so you can't build out those deeper nested paths like b.d.e. Also, that inner loop over Object.entries(v) is throwing you off; you don't need to iterate the child object's entries right away—let the recursion handle that.
Step-by-Step Solution Approach
- Pass the current path prefix to your recursive function (start with an empty string for the root level).
- For each key-value pair in the current object:
- Check if the value is a target entry (i.e., it's an object containing the
"="key). - If it is: add the full path (prefix + current key) to your results array.
- If it isn't: recursively traverse the value, updating the path prefix to
prefix + "." + key(make sure to avoid leading dots for root-level keys).
- Check if the value is a target entry (i.e., it's an object containing the
- Keep using your
isObjecthelper to ensure you're only processing valid non-array objects.
Working Code Implementation
function isObject(obj) { return typeof obj === "object" && !Array.isArray(obj) && obj !== null; } function nestedObject(obj) { const operator = "="; const attributes = []; // Recursive function with path prefix parameter function traverse(currentObj, currentPath = "") { if (!isObject(currentObj)) return; for (const [key, value] of Object.entries(currentObj)) { // Build the new path: handle root level (no leading dot) const newPath = currentPath ? `${currentPath}.${key}` : key; // Check if this value is our target entry ({ "=": value }) if (isObject(value) && operator in value) { attributes.push(newPath); } else { // Recurse into the nested object with the updated path traverse(value, newPath); } } } traverse(obj); return attributes; } // Test with your example object const obj = { a: { "=" : 0 }, b: { c: { "=" : 1 }, d: { e: { "=" : 2 }, f: { g: { "=" : 3 } } } } }; console.log(nestedObject(obj)); // Output: ["a", "b.c", "b.d.e", "b.d.f.g"]
Key Explanations
- Path Prefix Handling: The
currentPathparameter lets us carry over the path we've built so far. For root-level keys,currentPathis empty, sonewPathis just the key itself. For nested keys, we append.<key>to the existing path. - Target Entry Check: We check if the value is an object that contains our
operator("=")—this tells us we've reached the end of a path that needs to be added to the results. - Recursion Trigger: When we hit a nested object that's not a target entry, we call
traverseagain with that object and the updated path, letting the function handle the deeper levels.
This approach cleanly traverses every level of the object and builds the exact dotted paths you're expecting.
内容的提问来源于stack exchange,提问作者asnaeb
相关产品推荐
相关产品推荐

