Situation: I have a large object containing multiple sub and sub-sub objects, with properties containing multiple datatypes. For our purposes, this object looks something like this:
var object = { aProperty: { aSetting1: 1, aSetting2: 2, aSetting3: 3, aSetting4: 4, aSetting5: 5 }, bProperty: { bSetting1: { bPropertySubSetting : true }, bSetting2: "bString" }, cProperty: { cSetting: "cString" } }
I need to loop through this object and build a list of the keys that shows the hierarchy, so the list ends up looking like this:
aProperty.aSetting1 aProperty.aSetting2 aProperty.aSetting3 aProperty.aSetting4 aProperty.aSetting5 bProperty.bSetting1.bPropertySubSetting bProperty.bSetting2 cProperty.cSetting
I've got this function, which does loop through the object and spit out the keys, but not hierarchically:
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]); } } } }
Can somebody let me know how to do this? Here's a jsfiddle for you to mess with: http://jsfiddle.net/tbynA/
A for...in loop only iterates over enumerable, non-Symbol properties. Objects created from built–in constructors like Array and Object have inherited non–enumerable properties from Array.
Object. entries() is the recommended method for iterating over an object's properties in JavaScript. Since the method returns a multidimensional array, we can greatly simplify our code by using the array destructuring syntax to retrieve each property into a separate variable.
A recursive object type can repeat itself indefinitely or until some set limit is reached. The following object types are recursive within the IBM OpenPages® with Watson™ application: Business Entity (SOXBusEntity)
I made a FIDDLE for you. I am storing a stack
string and then output it, if the property is of primitive type:
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, '')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With