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
- Recursive Traversal: Use a helper function to traverse each level of the nested object, keeping track of the current path to each property.
- Path Construction: Build the dot-separated path incrementally as we dive deeper into nested structures.
- 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, orinproperties. 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/inplus 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
相关产品推荐
相关产品推荐

