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

JavaScript生成嵌套对象属性端点路径字符串方案问询

Solution: Flatten Nested Object to Path-Keyed Entries

To solve this problem, we need to recursively traverse a nested object and flatten it into a new object where each key is a dot-separated path to an endpoint, and the value is the endpoint itself. Endpoints are defined as either non-object types (strings, numbers, booleans, null) or objects containing at least one of min, max, or in properties.

Approach

  1. Recursive Traversal: Use a helper function to traverse each level of the nested object, keeping track of the current path to each property.
  2. Path Construction: Build the dot-separated path incrementally as we dive deeper into nested structures.
  3. Endpoint Detection: For each value, check if it qualifies as an endpoint:
    • Non-object types (including null) are immediately added to the result with their full path.
    • Objects are checked for the presence of min, max, or in properties. If found, they're added as endpoints; otherwise, we continue traversing their nested properties.

Code Implementation

function objPaths(nestedObj) {
  const flattened = {};

  function traverse(obj, currentPath) {
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        const value = obj[key];
        const newPath = currentPath ? `${currentPath}.${key}` : key;

        if (typeof value === 'object' && value !== null) {
          // Check if this object is an endpoint (has min/max/in)
          const isEndpoint = ['min', 'max', 'in'].some(prop => value.hasOwnProperty(prop));
          
          if (isEndpoint) {
            flattened[newPath] = value;
          } else {
            // Recurse into non-endpoint nested objects
            traverse(value, newPath);
          }
        } else {
          // Non-object types are direct endpoints
          flattened[newPath] = value;
        }
      }
    }
  }

  traverse(nestedObj, '');
  return flattened;
}

Example Usage

Let's test the function with your sample input:

const input = { a: { b: { c: { min: 1, max: 2 }, d: 1 } } };
console.log(objPaths(input));
// Output: { "a.b.c": { min: 1, max: 2 }, "a.b.d": 1 }

Edge Cases Handled

  • Null Values: Null is treated as a non-object endpoint, e.g., { a: null } becomes { "a": null }.
  • Endpoint Objects with Extra Properties: Objects containing min/max/in plus other properties are still considered endpoints, e.g., { a: { min: 0, label: "Range" } } becomes { "a": { min: 0, label: "Range" } }.
  • Arrays: Arrays are traversed like objects, with numeric indices included in the path, e.g., { a: [1, { max: 5 }] } becomes { "a.0": 1, "a.1": { max:5 } }.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:27:36