How does this code read for reading through an object, able to read objects within it:
var book = {
"main title": "Javascript",
"sub-title": "Def Guide",
"for": "all audiences",
author: {
firstname: "David",
surname: "Fatagans"
}
};
for (propName in book){
console.log("key: " + propName + " value: " + book[propName]);
if (typeof book[propName] === "object"){
for (innerObject in book[propName]){
console.log("key: " + innerObject + "value: " + book[propName][innerObject])
}
}
}
One way is to put the code into a function and call it recursively, something like:
The above will also show enumerable attributes on the object’s
[[Prototype]]chain. To ignore those, use a hasOwnProperty test:Be careful with passing host objects (e.g. DOM elements) to the function, extra precautions need to be taken with those.