Creating a Hierarchical Property List from Complex Objects Recursively
In situations where complex objects contain multiple sub-objects and properties with varying data types, the need arises to build a hierarchical list of those properties. To achieve this, a recursive looping approach is essential.
Given Problem:
An object is provided with the following structure:
<code class="javascript">var object = { aProperty: { aSetting1: 1, aSetting2: 2, aSetting3: 3, aSetting4: 4, aSetting5: 5 }, bProperty: { bSetting1: { bPropertySubSetting : true }, bSetting2: "bString" }, cProperty: { cSetting: "cString" } };</code>
Desired Output:
The goal is to create a list of keys that accurately reflects the hierarchy of the object:
aProperty.aSetting1 aProperty.aSetting2 aProperty.aSetting3 aProperty.aSetting4 aProperty.aSetting5 bProperty.bSetting1.bPropertySubSetting bProperty.bSetting2 cProperty.cSetting
Initial Solution:
<code class="javascript">function iterate(obj) { for (var property in obj) { if (obj.hasOwnProperty(property)) { if (typeof obj[property] == "object") { iterate(obj[property]); } else { console.log(property + " " + obj[property]); } } } }</code>
This function loops through the object and prints the keys, but it does not maintain the hierarchy.
Recursive Solution:
To preserve the hierarchy, we can maintain a stack string that represents the path of the current property. When a primitive property is encountered, the path is printed. For nested objects, the stack is updated, and the recursion continues.
<code class="javascript">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(property + " " + obj[property]); $('#output').append($("<div/>").text(stack + '.' + property)) } } } } iterate(object, '');</code>
Additional Notes:
The above is the detailed content of How to Create a Hierarchical Property List from Complex Objects Recursively in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!