递归遍历对象以构建属性列表 [英] Recursively looping through an object to build a property list
问题描述
情况:我有一个包含多个子对象和子子对象的大对象,其属性包含多种数据类型.为了我们的目的,这个对象看起来像这样:
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]);
}
}
}
}
谁能告诉我怎么做?这是一个 jsfiddle 供您使用:http://jsfiddle.net/tbynA/
Can somebody let me know how to do this? Here's a jsfiddle for you to mess with: http://jsfiddle.net/tbynA/
推荐答案
我做了一个 FIDDLE强> 给你.我存储一个 stack
字符串,然后输出它,如果属性是原始类型:
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, '')
这篇关于递归遍历对象以构建属性列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!