Problem:
Creating a flattened list of property keys from a complex object with multiple levels of nesting, while maintaining the hierarchy.
Underlying Data Structure:
The given object has a hierarchical structure with properties at different levels.
Desired Output:
A list of property keys that reflect the hierarchy.
Initial Approach:
A basic recursion function, iterate, is provided to loop through the object and print the property keys. However, it does not maintain the hierarchy.
Solution:
To account for the hierarchy, a stack variable is introduced to store the current path in the object. As the recursion function traverses the object, it appends the current property to the stack. When a primitive property is encountered, it is printed along with the concatenated stack, representing the full path to that property.
Revised Code:
<code class="js">function iterate(obj, stack) { for (var property in obj) { if (obj.hasOwnProperty(property)) { if (typeof obj[property] === "object") { iterate(obj[property], stack + "." + property); } else { console.log(stack + "." + property); $('#output').append($('<div>').text(stack + "." + property)); } } } } iterate(object, "");</code>
Updated Solution:
The updated solution in the referenced answer provides a cleaner implementation using a combination of map and reduce functions to recursively traverse the object and build the flattened list of property keys.
<code class="js">Object.keys(object).map(key => createPath(object, key, "")).reduce((a, b) => a.concat(b))</code>
Function Explanation:
The above is the detailed content of How to Flatten a Nested Object\'s Property List with Hierarchy?. For more information, please follow other related articles on the PHP Chinese website!