I have an object which has inner objects and properties defined like this:
var obj = {obj1 : { "prop1" : "nothing", "prop2" : "prop"},
obj2 : {"prop1" : "nothing", "prop2" : "prop"},
pr1 : "message",
pr2 : "mess"
};
Normally to iterate every property of an object , the for .. in
loop can d开发者_如何学JAVAo the trick
for (property in obj){
if (obj.hasOwnProperty(property)){
console.log(property + " " + obj[property]);
}
}
the console displayed :
obj1 [object Object] obj12 [object Object] pr1 message pr2 mess
However how to iterate the inner objects (obj1, obj2
) and their own properties (prop1,prop2
) ?
Recursion is your friend:
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]);
}
}
}
Note: don't forget to declare property
locally using var
!
That's great anwsers, although the array cases is not covered, here's my contribution:
var getProps = function (obj) {
for (var property in obj) {
if (obj.hasOwnProperty(property) && obj[property] != null) {
if (obj[property].constructor == Object) {
getProps(obj[property]);
} else if (obj[property].constructor == Array) {
for (var i = 0; i < obj[property].length; i++) {
getProps(obj[property][i]);
}
} else {
console.log(obj[property]);
}
}
}
}
getProps(myObject);
To simply display the object structure, I often use: console.log (JSON.stringify (obj))
You can use recursion to achieve that:
function Props(obj) {
function getProps(obj){
for (var property in obj) {
if (obj.hasOwnProperty(property)){
if (obj[property].constructor == Object) {
console.log('**Object -> '+property+': ');
getProps(obj[property]);
} else {
console.log(property + " " + obj[property]);
}
}
}
}
getProps(obj);
}
see http://jsfiddle.net/KooiInc/hg6dU/
精彩评论