本文介绍了如何迭代对象中的内部对象/属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个对象,其内部对象和属性定义如下:
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"
};
通常迭代对象的每个属性, for .. in
loop可以解决这个问题
Normally to iterate every property of an object , the for .. in
loop can do the trick
for (property in obj){
if (obj.hasOwnProperty(property)){
console.log(property + " " + obj[property]);
}
}
控制台显示:
obj1 [object Object]
obj12 [object Object]
pr1 message
pr2 mess
但是如何迭代内部对象( obj1,obj2
)和他们自己的属性( prop1,prop2
)?
However how to iterate the inner objects (obj1, obj2
) and their own properties (prop1,prop2
) ?
推荐答案
递归是你的朋友:
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]);
}
}
}
注意:不要忘记在本地使用 var
声明属性
!
Note: don't forget to declare property
locally using var
!
这篇关于如何迭代对象中的内部对象/属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!