Recursive Property List Construction
To traverse a complex object and extract a hierarchical list of its properties, consider using a recursive function. This technique effectively captures the nested relationships within the object's structure.
Our sample object, with its nested properties, serves as a case in point:
var object = {
aProperty: {
aSetting1: 1,
aSetting2: 2,
aSetting3: 3,
aSetting4: 4,
aSetting5: 5
},
bProperty: {
bSetting1: {
bPropertySubSetting : true
},
bSetting2: "bString"
},
cProperty: {
cSetting: "cString"
}
}
To construct the desired list of property keys hierarchically, we can employ a recursive function like this:
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($("").text(stack '.' property))
}
}
}
}
iterate(object, '')This function operates recursively, starting with the initial object and an empty stack. As it explores the object, it constructs the stack string representing the hierarchical path to each property.
- For primitive type properties, the function logs the property key and its value.
- For nested objects, the function recursively calls itself, passing in the nested object and appending the property key to the stack string.
The result is a list of property keys, capturing the hierarchical structure of the original object.
This solution effectively integrates recursion with property iteration, providing a comprehensive approach to constructing a hierarchical list of object properties.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3