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

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

  1. Pass the current path prefix to your recursive function (start with an empty string for the root level).
  2. 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).
  3. Keep using your isObject helper 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 currentPath parameter lets us carry over the path we've built so far. For root-level keys, currentPath is empty, so newPath is 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 traverse again 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 19:59:08